(bug 14990) Parser tests works again with PostgreSQL
[lhc/web/wiklou.git] / maintenance / parserTests.inc
1 <?php
2 # Copyright (C) 2004 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 $options = array( 'quick', 'color', 'quiet', 'help', 'show-output', 'record' );
29 $optionsWithArgs = array( 'regex', 'seed' );
30
31 require_once( 'commandLine.inc' );
32 require_once( "$IP/maintenance/parserTestsParserHook.php" );
33 require_once( "$IP/maintenance/parserTestsStaticParserHook.php" );
34 require_once( "$IP/maintenance/parserTestsParserTime.php" );
35
36 /**
37 * @ingroup Maintenance
38 */
39 class ParserTest {
40 /**
41 * boolean $color whereas output should be colorized
42 */
43 private $color;
44
45 /**
46 * boolean $showOutput Show test output
47 */
48 private $showOutput;
49
50 /**
51 * boolean $useTemporaryTables Use temporary tables for the temporary database
52 */
53 private $useTemporaryTables = true;
54
55 /**
56 * boolean $databaseSetupDone True if the database has been set up
57 */
58 private $databaseSetupDone = false;
59
60 /**
61 * string $oldTablePrefix Original table prefix
62 */
63 private $oldTablePrefix;
64
65 private $maxFuzzTestLength = 300;
66 private $fuzzSeed = 0;
67 private $memoryLimit = 50;
68
69 /**
70 * Sets terminal colorization and diff/quick modes depending on OS and
71 * command-line options (--color and --quick).
72 */
73 public function ParserTest() {
74 global $options;
75
76 # Only colorize output if stdout is a terminal.
77 $this->color = !wfIsWindows() && posix_isatty(1);
78
79 if( isset( $options['color'] ) ) {
80 switch( $options['color'] ) {
81 case 'no':
82 $this->color = false;
83 break;
84 case 'yes':
85 default:
86 $this->color = true;
87 break;
88 }
89 }
90 $this->term = $this->color
91 ? new AnsiTermColorer()
92 : new DummyTermColorer();
93
94 $this->showDiffs = !isset( $options['quick'] );
95 $this->showProgress = !isset( $options['quiet'] );
96 $this->showFailure = !(
97 isset( $options['quiet'] )
98 && ( isset( $options['record'] )
99 || isset( $options['compare'] ) ) ); // redundant output
100
101 $this->showOutput = isset( $options['show-output'] );
102
103
104 if (isset($options['regex'])) {
105 if ( isset( $options['record'] ) ) {
106 echo "Warning: --record cannot be used with --regex, disabling --record\n";
107 unset( $options['record'] );
108 }
109 $this->regex = $options['regex'];
110 } else {
111 # Matches anything
112 $this->regex = '';
113 }
114
115 if( isset( $options['record'] ) ) {
116 $this->recorder = new DbTestRecorder( $this );
117 } elseif( isset( $options['compare'] ) ) {
118 $this->recorder = new DbTestPreviewer( $this );
119 } else {
120 $this->recorder = new TestRecorder( $this );
121 }
122 $this->keepUploads = isset( $options['keep-uploads'] );
123
124 if ( isset( $options['seed'] ) ) {
125 $this->fuzzSeed = intval( $options['seed'] ) - 1;
126 }
127
128 $this->hooks = array();
129 $this->functionHooks = array();
130 }
131
132 /**
133 * Remove last character if it is a newline
134 */
135 private 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 $dict = $this->getFuzzInput( $filenames );
150 $dictSize = strlen( $dict );
151 $logMaxLength = log( $this->maxFuzzTestLength );
152 $this->setupDatabase();
153 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
154
155 $numTotal = 0;
156 $numSuccess = 0;
157 $user = new User;
158 $opts = ParserOptions::newFromUser( $user );
159 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
160
161 while ( true ) {
162 // Generate test input
163 mt_srand( ++$this->fuzzSeed );
164 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
165 $input = '';
166 while ( strlen( $input ) < $totalLength ) {
167 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
168 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
169 $offset = mt_rand( 0, $dictSize - $hairLength );
170 $input .= substr( $dict, $offset, $hairLength );
171 }
172
173 $this->setupGlobals();
174 $parser = $this->getParser();
175 // Run the test
176 try {
177 $parser->parse( $input, $title, $opts );
178 $fail = false;
179 } catch ( Exception $exception ) {
180 $fail = true;
181 }
182
183 if ( $fail ) {
184 echo "Test failed with seed {$this->fuzzSeed}\n";
185 echo "Input:\n";
186 var_dump( $input );
187 echo "\n\n";
188 echo "$exception\n";
189 } else {
190 $numSuccess++;
191 }
192 $numTotal++;
193 $this->teardownGlobals();
194 $parser->__destruct();
195
196 if ( $numTotal % 100 == 0 ) {
197 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
198 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
199 if ( $usage > 90 ) {
200 echo "Out of memory:\n";
201 $memStats = $this->getMemoryBreakdown();
202 foreach ( $memStats as $name => $usage ) {
203 echo "$name: $usage\n";
204 }
205 $this->abort();
206 }
207 }
208 }
209 }
210
211 /**
212 * Get an input dictionary from a set of parser test files
213 */
214 function getFuzzInput( $filenames ) {
215 $dict = '';
216 foreach( $filenames as $filename ) {
217 $contents = file_get_contents( $filename );
218 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
219 foreach ( $matches[1] as $match ) {
220 $dict .= $match . "\n";
221 }
222 }
223 return $dict;
224 }
225
226 /**
227 * Get a memory usage breakdown
228 */
229 function getMemoryBreakdown() {
230 $memStats = array();
231 foreach ( $GLOBALS as $name => $value ) {
232 $memStats['$'.$name] = strlen( serialize( $value ) );
233 }
234 $classes = get_declared_classes();
235 foreach ( $classes as $class ) {
236 $rc = new ReflectionClass( $class );
237 $props = $rc->getStaticProperties();
238 $memStats[$class] = strlen( serialize( $props ) );
239 $methods = $rc->getMethods();
240 foreach ( $methods as $method ) {
241 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
242 }
243 }
244 $functions = get_defined_functions();
245 foreach ( $functions['user'] as $function ) {
246 $rf = new ReflectionFunction( $function );
247 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
248 }
249 asort( $memStats );
250 return $memStats;
251 }
252
253 function abort() {
254 $this->abort();
255 }
256
257 /**
258 * Run a series of tests listed in the given text files.
259 * Each test consists of a brief description, wikitext input,
260 * and the expected HTML output.
261 *
262 * Prints status updates on stdout and counts up the total
263 * number and percentage of passed tests.
264 *
265 * @param array of strings $filenames
266 * @return bool True if passed all tests, false if any tests failed.
267 */
268 public function runTestsFromFiles( $filenames ) {
269 $this->recorder->start();
270 $this->setupDatabase();
271 $ok = true;
272 foreach( $filenames as $filename ) {
273 $ok = $this->runFile( $filename ) && $ok;
274 }
275 $this->teardownDatabase();
276 $this->recorder->report();
277 $this->recorder->end();
278 return $ok;
279 }
280
281 private function runFile( $filename ) {
282 $infile = fopen( $filename, 'rt' );
283 if( !$infile ) {
284 wfDie( "Couldn't open $filename\n" );
285 } else {
286 global $IP;
287 $relative = wfRelativePath( $filename, $IP );
288 $this->showRunFile( $relative );
289 }
290
291 $data = array();
292 $section = null;
293 $n = 0;
294 $ok = true;
295 while( false !== ($line = fgets( $infile ) ) ) {
296 $n++;
297 $matches = array();
298 if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
299 $section = strtolower( $matches[1] );
300 if( $section == 'endarticle') {
301 if( !isset( $data['text'] ) ) {
302 wfDie( "'endarticle' without 'text' at line $n of $filename\n" );
303 }
304 if( !isset( $data['article'] ) ) {
305 wfDie( "'endarticle' without 'article' at line $n of $filename\n" );
306 }
307 $this->addArticle($this->chomp($data['article']), $this->chomp($data['text']), $n);
308 $data = array();
309 $section = null;
310 continue;
311 }
312 if( $section == 'endhooks' ) {
313 if( !isset( $data['hooks'] ) ) {
314 wfDie( "'endhooks' without 'hooks' at line $n of $filename\n" );
315 }
316 foreach( explode( "\n", $data['hooks'] ) as $line ) {
317 $line = trim( $line );
318 if( $line ) {
319 $this->requireHook( $line );
320 }
321 }
322 $data = array();
323 $section = null;
324 continue;
325 }
326 if( $section == 'endfunctionhooks' ) {
327 if( !isset( $data['functionhooks'] ) ) {
328 wfDie( "'endfunctionhooks' without 'functionhooks' at line $n of $filename\n" );
329 }
330 foreach( explode( "\n", $data['functionhooks'] ) as $line ) {
331 $line = trim( $line );
332 if( $line ) {
333 $this->requireFunctionHook( $line );
334 }
335 }
336 $data = array();
337 $section = null;
338 continue;
339 }
340 if( $section == 'end' ) {
341 if( !isset( $data['test'] ) ) {
342 wfDie( "'end' without 'test' at line $n of $filename\n" );
343 }
344 if( !isset( $data['input'] ) ) {
345 wfDie( "'end' without 'input' at line $n of $filename\n" );
346 }
347 if( !isset( $data['result'] ) ) {
348 wfDie( "'end' without 'result' at line $n of $filename\n" );
349 }
350 if( !isset( $data['options'] ) ) {
351 $data['options'] = '';
352 }
353 else {
354 $data['options'] = $this->chomp( $data['options'] );
355 }
356 if (preg_match('/\\bdisabled\\b/i', $data['options'])
357 || !preg_match("/{$this->regex}/i", $data['test'])) {
358 # disabled test
359 $data = array();
360 $section = null;
361 continue;
362 }
363 $result = $this->runTest(
364 $this->chomp( $data['test'] ),
365 $this->chomp( $data['input'] ),
366 $this->chomp( $data['result'] ),
367 $this->chomp( $data['options'] ) );
368 $ok = $ok && $result;
369 $this->recorder->record( $this->chomp( $data['test'] ), $result );
370 $data = array();
371 $section = null;
372 continue;
373 }
374 if ( isset ($data[$section] ) ) {
375 wfDie( "duplicate section '$section' at line $n of $filename\n" );
376 }
377 $data[$section] = '';
378 continue;
379 }
380 if( $section ) {
381 $data[$section] .= $line;
382 }
383 }
384 if ( $this->showProgress ) {
385 print "\n";
386 }
387 return $ok;
388 }
389
390 /**
391 * Get a Parser object
392 */
393 function getParser() {
394 global $wgParserConf;
395 $class = $wgParserConf['class'];
396 $parser = new $class( $wgParserConf );
397 foreach( $this->hooks as $tag => $callback ) {
398 $parser->setHook( $tag, $callback );
399 }
400 foreach( $this->functionHooks as $tag => $bits ) {
401 list( $callback, $flags ) = $bits;
402 $parser->setFunctionHook( $tag, $callback, $flags );
403 }
404 wfRunHooks( 'ParserTestParser', array( &$parser ) );
405 return $parser;
406 }
407
408 /**
409 * Run a given wikitext input through a freshly-constructed wiki parser,
410 * and compare the output against the expected results.
411 * Prints status and explanatory messages to stdout.
412 *
413 * @param string $input Wikitext to try rendering
414 * @param string $result Result to output
415 * @return bool
416 */
417 private function runTest( $desc, $input, $result, $opts ) {
418 if( $this->showProgress ) {
419 $this->showTesting( $desc );
420 }
421
422 $this->setupGlobals($opts);
423
424 $user = new User();
425 $options = ParserOptions::newFromUser( $user );
426
427 if (preg_match('/\\bmath\\b/i', $opts)) {
428 # XXX this should probably be done by the ParserOptions
429 $options->setUseTex(true);
430 }
431
432 $m = array();
433 if (preg_match('/title=\[\[(.*)\]\]/', $opts, $m)) {
434 $titleText = $m[1];
435 }
436 else {
437 $titleText = 'Parser test';
438 }
439
440 $noxml = (bool)preg_match( '~\\b noxml \\b~x', $opts );
441 $parser = $this->getParser();
442 $title =& Title::makeTitle( NS_MAIN, $titleText );
443
444 $matches = array();
445 if (preg_match('/\\bpst\\b/i', $opts)) {
446 $out = $parser->preSaveTransform( $input, $title, $user, $options );
447 } elseif (preg_match('/\\bmsg\\b/i', $opts)) {
448 $out = $parser->transformMsg( $input, $options );
449 } elseif( preg_match( '/\\bsection=([\w-]+)\b/i', $opts, $matches ) ) {
450 $section = $matches[1];
451 $out = $parser->getSection( $input, $section );
452 } elseif( preg_match( '/\\breplace=([\w-]+),"(.*?)"/i', $opts, $matches ) ) {
453 $section = $matches[1];
454 $replace = $matches[2];
455 $out = $parser->replaceSection( $input, $section, $replace );
456 } else {
457 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
458 $out = $output->getText();
459
460 if (preg_match('/\\bill\\b/i', $opts)) {
461 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
462 } else if (preg_match('/\\bcat\\b/i', $opts)) {
463 global $wgOut;
464 $wgOut->addCategoryLinks($output->getCategories());
465 $cats = $wgOut->getCategoryLinks();
466 if ( isset( $cats['normal'] ) ) {
467 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
468 } else {
469 $out = '';
470 }
471 }
472
473 $result = $this->tidy($result);
474 }
475
476 $this->teardownGlobals();
477
478 if( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
479 return $this->showSuccess( $desc );
480 } else {
481 return $this->showFailure( $desc, $result, $out );
482 }
483 }
484
485
486 /**
487 * Use a regex to find out the value of an option
488 * @param $regex A regex, the first group will be the value returned
489 * @param $opts Options line to look in
490 * @param $defaults Default value returned if the regex does not match
491 */
492 private static function getOptionValue( $regex, $opts, $default ) {
493 $m = array();
494 if( preg_match( $regex, $opts, $m ) ) {
495 return $m[1];
496 } else {
497 return $default;
498 }
499 }
500
501 /**
502 * Set up the global variables for a consistent environment for each test.
503 * Ideally this should replace the global configuration entirely.
504 */
505 private function setupGlobals($opts = '') {
506 if( !isset( $this->uploadDir ) ) {
507 $this->uploadDir = $this->setupUploadDir();
508 }
509
510 # Find out values for some special options.
511 $lang =
512 self::getOptionValue( '/language=([a-z]+(?:_[a-z]+)?)/', $opts, 'en' );
513 $variant =
514 self::getOptionValue( '/variant=([a-z]+(?:-[a-z]+)?)/', $opts, false );
515 $maxtoclevel =
516 self::getOptionValue( '/wgMaxTocLevel=(\d+)/', $opts, 999 );
517 $linkHolderBatchSize =
518 self::getOptionValue( '/wgLinkHolderBatchSize=(\d+)/', $opts, 1000 );
519
520 $settings = array(
521 'wgServer' => 'http://localhost',
522 'wgScript' => '/index.php',
523 'wgScriptPath' => '/',
524 'wgArticlePath' => '/wiki/$1',
525 'wgActionPaths' => array(),
526 'wgLocalFileRepo' => array(
527 'class' => 'LocalRepo',
528 'name' => 'local',
529 'directory' => $this->uploadDir,
530 'url' => 'http://example.com/images',
531 'hashLevels' => 2,
532 'transformVia404' => false,
533 ),
534 'wgEnableUploads' => true,
535 'wgStyleSheetPath' => '/skins',
536 'wgSitename' => 'MediaWiki',
537 'wgServerName' => 'Britney Spears',
538 'wgLanguageCode' => $lang,
539 'wgContLanguageCode' => $lang,
540 'wgDBprefix' => 'parsertest_',
541 'wgRawHtml' => preg_match('/\\brawhtml\\b/i', $opts),
542 'wgLang' => null,
543 'wgContLang' => null,
544 'wgNamespacesWithSubpages' => array( 0 => preg_match('/\\bsubpage\\b/i', $opts)),
545 'wgMaxTocLevel' => $maxtoclevel,
546 'wgCapitalLinks' => true,
547 'wgNoFollowLinks' => true,
548 'wgNoFollowDomainExceptions' => array(),
549 'wgThumbnailScriptPath' => false,
550 'wgUseTeX' => false,
551 'wgLocaltimezone' => 'UTC',
552 'wgAllowExternalImages' => true,
553 'wgUseTidy' => false,
554 'wgDefaultLanguageVariant' => $variant,
555 'wgVariantArticlePath' => false,
556 'wgGroupPermissions' => array( '*' => array(
557 'createaccount' => true,
558 'read' => true,
559 'edit' => true,
560 'createpage' => true,
561 'createtalk' => true,
562 ) ),
563 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
564 'wgDefaultExternalStore' => array(),
565 'wgForeignFileRepos' => array(),
566 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
567 'wgEnforceHtmlIds' => true,
568 'wgExternalLinkTarget' => false,
569 'wgAlwaysUseTidy' => false,
570 );
571 $this->savedGlobals = array();
572 foreach( $settings as $var => $val ) {
573 $this->savedGlobals[$var] = $GLOBALS[$var];
574 $GLOBALS[$var] = $val;
575 }
576 $langObj = Language::factory( $lang );
577 $GLOBALS['wgLang'] = $langObj;
578 $GLOBALS['wgContLang'] = $langObj;
579 $GLOBALS['wgMemc'] = new FakeMemCachedClient;
580
581 //$GLOBALS['wgMessageCache'] = new MessageCache( new BagOStuff(), false, 0, $GLOBALS['wgDBname'] );
582
583 global $wgUser;
584 $wgUser = new User();
585 }
586
587 /**
588 * List of temporary tables to create, without prefix.
589 * Some of these probably aren't necessary.
590 */
591 private function listTables() {
592 global $wgDBtype;
593 $tables = array('user', 'page', 'page_restrictions',
594 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
595 'categorylinks', 'templatelinks', 'externallinks', 'langlinks',
596 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
597 'recentchanges', 'watchlist', 'math', 'interwiki',
598 'querycache', 'objectcache', 'job', 'redirect', 'querycachetwo',
599 'archive', 'user_groups', 'page_props', 'category'
600 );
601
602 if ($wgDBtype === 'mysql')
603 array_push( $tables, 'searchindex' );
604
605 // Allow extensions to add to the list of tables to duplicate;
606 // may be necessary if they hook into page save or other code
607 // which will require them while running tests.
608 wfRunHooks( 'ParserTestTables', array( &$tables ) );
609
610 return $tables;
611 }
612
613 /**
614 * Set up a temporary set of wiki tables to work with for the tests.
615 * Currently this will only be done once per run, and any changes to
616 * the db will be visible to later tests in the run.
617 */
618 private function setupDatabase() {
619 global $wgDBprefix, $wgDBtype;
620 if ( $this->databaseSetupDone ) {
621 return;
622 }
623 if ( $wgDBprefix === 'parsertest_' ) {
624 throw new MWException( 'setupDatabase should be called before setupGlobals' );
625 }
626 $this->databaseSetupDone = true;
627 $this->oldTablePrefix = $wgDBprefix;
628
629 # CREATE TEMPORARY TABLE breaks if there is more than one server
630 # FIXME: r40209 makes temporary tables break even with just one server
631 # FIXME: (bug 15892); disabling the feature entirely as a temporary fix
632 if ( true || wfGetLB()->getServerCount() != 1 ) {
633 $this->useTemporaryTables = false;
634 }
635
636 $temporary = $this->useTemporaryTables ? 'TEMPORARY' : '';
637
638 $db = wfGetDB( DB_MASTER );
639 $tables = $this->listTables();
640
641 if ( !( $wgDBtype == 'mysql' && strcmp( $db->getServerVersion(), '4.1' ) < 0 ) ) {
642 # Database that supports CREATE TABLE ... LIKE
643
644 if( $wgDBtype == 'postgres' ) {
645 $def = 'INCLUDING DEFAULTS';
646 $temporary = 'TEMPORARY';
647 } else {
648 $def = '';
649 }
650 foreach ( $tables as $tbl ) {
651 # Clean up from previous aborted run. So that table escaping
652 # works correctly across DB engines, we need to change the pre-
653 # fix back and forth so tableName() works right.
654 $this->changePrefix( $this->oldTablePrefix );
655 $oldTableName = $db->tableName( $tbl );
656 $this->changePrefix( 'parsertest_' );
657 $newTableName = $db->tableName( $tbl );
658
659 if ( $db->tableExists( $tbl ) && $wgDBtype != 'postgres' ) {
660 $db->query( "DROP TABLE $newTableName" );
661 }
662 # Create new table
663 $db->query( "CREATE $temporary TABLE $newTableName (LIKE $oldTableName $def)" );
664 }
665 } else {
666 # Hack for MySQL versions < 4.1, which don't support
667 # "CREATE TABLE ... LIKE". Note that
668 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
669 # would not create the indexes we need....
670 #
671 # Note that we don't bother changing around the prefixes here be-
672 # cause we know we're using MySQL anyway.
673 foreach ($tables as $tbl) {
674 $oldTableName = $db->tableName( $tbl );
675 $res = $db->query("SHOW CREATE TABLE $oldTableName");
676 $row = $db->fetchRow($res);
677 $create = $row[1];
678 $create_tmp = preg_replace('/CREATE TABLE `(.*?)`/',
679 "CREATE $temporary TABLE `parsertest_$tbl`", $create);
680 if ($create === $create_tmp) {
681 # Couldn't do replacement
682 wfDie("could not create temporary table $tbl");
683 }
684 $db->query($create_tmp);
685 }
686 }
687
688 $this->changePrefix( 'parsertest_' );
689
690 # Hack: insert a few Wikipedia in-project interwiki prefixes,
691 # for testing inter-language links
692 $db->insert( 'interwiki', array(
693 array( 'iw_prefix' => 'wikipedia',
694 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
695 'iw_local' => 0 ),
696 array( 'iw_prefix' => 'meatball',
697 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
698 'iw_local' => 0 ),
699 array( 'iw_prefix' => 'zh',
700 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
701 'iw_local' => 1 ),
702 array( 'iw_prefix' => 'es',
703 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
704 'iw_local' => 1 ),
705 array( 'iw_prefix' => 'fr',
706 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
707 'iw_local' => 1 ),
708 array( 'iw_prefix' => 'ru',
709 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
710 'iw_local' => 1 ),
711 ) );
712
713 # Hack: Insert an image to work with
714 $db->insert( 'image', array(
715 'img_name' => 'Foobar.jpg',
716 'img_size' => 12345,
717 'img_description' => 'Some lame file',
718 'img_user' => 1,
719 'img_user_text' => 'WikiSysop',
720 'img_timestamp' => $db->timestamp( '20010115123500' ),
721 'img_width' => 1941,
722 'img_height' => 220,
723 'img_bits' => 24,
724 'img_media_type' => MEDIATYPE_BITMAP,
725 'img_major_mime' => "image",
726 'img_minor_mime' => "jpeg",
727 'img_metadata' => serialize( array() ),
728 ) );
729
730 # Update certain things in site_stats
731 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 1, 'ss_good_articles' => 1 ) );
732 }
733
734 /**
735 * Change the table prefix on all open DB connections/
736 */
737 protected function changePrefix( $prefix ) {
738 global $wgDBprefix;
739 wfGetLBFactory()->forEachLB( array( $this, 'changeLBPrefix' ), array( $prefix ) );
740 $wgDBprefix = $prefix;
741 }
742
743 public function changeLBPrefix( $lb, $prefix ) {
744 $lb->forEachOpenConnection( array( $this, 'changeDBPrefix' ), array( $prefix ) );
745 }
746
747 public function changeDBPrefix( $db, $prefix ) {
748 $db->tablePrefix( $prefix );
749 }
750
751 private function teardownDatabase() {
752 global $wgDBprefix;
753 if ( !$this->databaseSetupDone ) {
754 return;
755 }
756 $this->changePrefix( $this->oldTablePrefix );
757 $this->databaseSetupDone = false;
758 if ( $this->useTemporaryTables ) {
759 # Don't need to do anything
760 return;
761 }
762
763 /*
764 $tables = $this->listTables();
765 $db = wfGetDB( DB_MASTER );
766 foreach ( $tables as $table ) {
767 $db->query( "DROP TABLE `parsertest_$table`" );
768 }*/
769 }
770
771 /**
772 * Create a dummy uploads directory which will contain a couple
773 * of files in order to pass existence tests.
774 * @return string The directory
775 */
776 private function setupUploadDir() {
777 global $IP;
778 if ( $this->keepUploads ) {
779 $dir = wfTempDir() . '/mwParser-images';
780 if ( is_dir( $dir ) ) {
781 return $dir;
782 }
783 } else {
784 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
785 }
786
787 wfDebug( "Creating upload directory $dir\n" );
788 if ( file_exists( $dir ) ) {
789 wfDebug( "Already exists!\n" );
790 return $dir;
791 }
792 wfMkdirParents( $dir . '/3/3a' );
793 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
794 return $dir;
795 }
796
797 /**
798 * Restore default values and perform any necessary clean-up
799 * after each test runs.
800 */
801 private function teardownGlobals() {
802 RepoGroup::destroySingleton();
803 FileCache::destroySingleton();
804 LinkCache::singleton()->clear();
805 foreach( $this->savedGlobals as $var => $val ) {
806 $GLOBALS[$var] = $val;
807 }
808 if( isset( $this->uploadDir ) ) {
809 $this->teardownUploadDir( $this->uploadDir );
810 unset( $this->uploadDir );
811 }
812 }
813
814 /**
815 * Remove the dummy uploads directory
816 */
817 private function teardownUploadDir( $dir ) {
818 if ( $this->keepUploads ) {
819 return;
820 }
821
822 // delete the files first, then the dirs.
823 self::deleteFiles(
824 array (
825 "$dir/3/3a/Foobar.jpg",
826 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
827 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
828 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
829 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
830 )
831 );
832
833 self::deleteDirs(
834 array (
835 "$dir/3/3a",
836 "$dir/3",
837 "$dir/thumb/6/65",
838 "$dir/thumb/6",
839 "$dir/thumb/3/3a/Foobar.jpg",
840 "$dir/thumb/3/3a",
841 "$dir/thumb/3",
842 "$dir/thumb",
843 "$dir",
844 )
845 );
846 }
847
848 /**
849 * Delete the specified files, if they exist.
850 * @param array $files full paths to files to delete.
851 */
852 private static function deleteFiles( $files ) {
853 foreach( $files as $file ) {
854 if( file_exists( $file ) ) {
855 unlink( $file );
856 }
857 }
858 }
859
860 /**
861 * Delete the specified directories, if they exist. Must be empty.
862 * @param array $dirs full paths to directories to delete.
863 */
864 private static function deleteDirs( $dirs ) {
865 foreach( $dirs as $dir ) {
866 if( is_dir( $dir ) ) {
867 rmdir( $dir );
868 }
869 }
870 }
871
872 /**
873 * "Running test $desc..."
874 */
875 protected function showTesting( $desc ) {
876 print "Running test $desc... ";
877 }
878
879 /**
880 * Print a happy success message.
881 *
882 * @param string $desc The test name
883 * @return bool
884 */
885 protected function showSuccess( $desc ) {
886 if( $this->showProgress ) {
887 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
888 }
889 return true;
890 }
891
892 /**
893 * Print a failure message and provide some explanatory output
894 * about what went wrong if so configured.
895 *
896 * @param string $desc The test name
897 * @param string $result Expected HTML output
898 * @param string $html Actual HTML output
899 * @return bool
900 */
901 protected function showFailure( $desc, $result, $html ) {
902 if( $this->showFailure ) {
903 if( !$this->showProgress ) {
904 # In quiet mode we didn't show the 'Testing' message before the
905 # test, in case it succeeded. Show it now:
906 $this->showTesting( $desc );
907 }
908 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
909 if ( $this->showOutput ) {
910 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
911 }
912 if( $this->showDiffs ) {
913 print $this->quickDiff( $result, $html );
914 if( !$this->wellFormed( $html ) ) {
915 print "XML error: $this->mXmlError\n";
916 }
917 }
918 }
919 return false;
920 }
921
922 /**
923 * Run given strings through a diff and return the (colorized) output.
924 * Requires writable /tmp directory and a 'diff' command in the PATH.
925 *
926 * @param string $input
927 * @param string $output
928 * @param string $inFileTail Tailing for the input file name
929 * @param string $outFileTail Tailing for the output file name
930 * @return string
931 */
932 protected function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
933 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
934
935 $infile = "$prefix-$inFileTail";
936 $this->dumpToFile( $input, $infile );
937
938 $outfile = "$prefix-$outFileTail";
939 $this->dumpToFile( $output, $outfile );
940
941 $diff = `diff -au $infile $outfile`;
942 unlink( $infile );
943 unlink( $outfile );
944
945 return $this->colorDiff( $diff );
946 }
947
948 /**
949 * Write the given string to a file, adding a final newline.
950 *
951 * @param string $data
952 * @param string $filename
953 */
954 private function dumpToFile( $data, $filename ) {
955 $file = fopen( $filename, "wt" );
956 fwrite( $file, $data . "\n" );
957 fclose( $file );
958 }
959
960 /**
961 * Colorize unified diff output if set for ANSI color output.
962 * Subtractions are colored blue, additions red.
963 *
964 * @param string $text
965 * @return string
966 */
967 protected function colorDiff( $text ) {
968 return preg_replace(
969 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
970 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
971 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
972 $text );
973 }
974
975 /**
976 * Show "Reading tests from ..."
977 *
978 * @param String $path
979 */
980 protected function showRunFile( $path ){
981 print $this->term->color( 1 ) .
982 "Reading tests from \"$path\"..." .
983 $this->term->reset() .
984 "\n";
985 }
986
987 /**
988 * Insert a temporary test article
989 * @param string $name the title, including any prefix
990 * @param string $text the article text
991 * @param int $line the input line number, for reporting errors
992 */
993 private function addArticle($name, $text, $line) {
994 $this->setupGlobals();
995 $title = Title::newFromText( $name );
996 if ( is_null($title) ) {
997 wfDie( "invalid title at line $line\n" );
998 }
999
1000 $aid = $title->getArticleID( GAID_FOR_UPDATE );
1001 if ($aid != 0) {
1002 wfDie( "duplicate article at line $line\n" );
1003 }
1004
1005 $art = new Article($title);
1006 $art->insertNewArticle($text, '', false, false );
1007 $this->teardownGlobals();
1008 }
1009
1010 /**
1011 * Steal a callback function from the primary parser, save it for
1012 * application to our scary parser. If the hook is not installed,
1013 * die a painful dead to warn the others.
1014 * @param string $name
1015 */
1016 private function requireHook( $name ) {
1017 global $wgParser;
1018 if( isset( $wgParser->mTagHooks[$name] ) ) {
1019 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1020 } else {
1021 wfDie( "This test suite requires the '$name' hook extension.\n" );
1022 }
1023 }
1024
1025 /**
1026 * Steal a callback function from the primary parser, save it for
1027 * application to our scary parser. If the hook is not installed,
1028 * die a painful dead to warn the others.
1029 * @param string $name
1030 */
1031 private function requireFunctionHook( $name ) {
1032 global $wgParser;
1033 if( isset( $wgParser->mFunctionHooks[$name] ) ) {
1034 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1035 } else {
1036 wfDie( "This test suite requires the '$name' function hook extension.\n" );
1037 }
1038 }
1039
1040 /*
1041 * Run the "tidy" command on text if the $wgUseTidy
1042 * global is true
1043 *
1044 * @param string $text the text to tidy
1045 * @return string
1046 * @static
1047 */
1048 private function tidy( $text ) {
1049 global $wgUseTidy;
1050 if ($wgUseTidy) {
1051 $text = Parser::tidy($text);
1052 }
1053 return $text;
1054 }
1055
1056 private function wellFormed( $text ) {
1057 $html =
1058 Sanitizer::hackDocType() .
1059 '<html>' .
1060 $text .
1061 '</html>';
1062
1063 $parser = xml_parser_create( "UTF-8" );
1064
1065 # case folding violates XML standard, turn it off
1066 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1067
1068 if( !xml_parse( $parser, $html, true ) ) {
1069 $err = xml_error_string( xml_get_error_code( $parser ) );
1070 $position = xml_get_current_byte_index( $parser );
1071 $fragment = $this->extractFragment( $html, $position );
1072 $this->mXmlError = "$err at byte $position:\n$fragment";
1073 xml_parser_free( $parser );
1074 return false;
1075 }
1076 xml_parser_free( $parser );
1077 return true;
1078 }
1079
1080 private function extractFragment( $text, $position ) {
1081 $start = max( 0, $position - 10 );
1082 $before = $position - $start;
1083 $fragment = '...' .
1084 $this->term->color( 34 ) .
1085 substr( $text, $start, $before ) .
1086 $this->term->color( 0 ) .
1087 $this->term->color( 31 ) .
1088 $this->term->color( 1 ) .
1089 substr( $text, $position, 1 ) .
1090 $this->term->color( 0 ) .
1091 $this->term->color( 34 ) .
1092 substr( $text, $position + 1, 9 ) .
1093 $this->term->color( 0 ) .
1094 '...';
1095 $display = str_replace( "\n", ' ', $fragment );
1096 $caret = ' ' .
1097 str_repeat( ' ', $before ) .
1098 $this->term->color( 31 ) .
1099 '^' .
1100 $this->term->color( 0 );
1101 return "$display\n$caret";
1102 }
1103 }
1104
1105 class AnsiTermColorer {
1106 function __construct() {
1107 }
1108
1109 /**
1110 * Return ANSI terminal escape code for changing text attribs/color
1111 *
1112 * @param string $color Semicolon-separated list of attribute/color codes
1113 * @return string
1114 */
1115 public function color( $color ) {
1116 global $wgCommandLineDarkBg;
1117 $light = $wgCommandLineDarkBg ? "1;" : "0;";
1118 return "\x1b[{$light}{$color}m";
1119 }
1120
1121 /**
1122 * Return ANSI terminal escape code for restoring default text attributes
1123 *
1124 * @return string
1125 */
1126 public function reset() {
1127 return $this->color( 0 );
1128 }
1129 }
1130
1131 /* A colour-less terminal */
1132 class DummyTermColorer {
1133 public function color( $color ) {
1134 return '';
1135 }
1136
1137 public function reset() {
1138 return '';
1139 }
1140 }
1141
1142 class TestRecorder {
1143 var $parent;
1144 var $term;
1145
1146 function __construct( $parent ) {
1147 $this->parent = $parent;
1148 $this->term = $parent->term;
1149 }
1150
1151 function start() {
1152 $this->total = 0;
1153 $this->success = 0;
1154 }
1155
1156 function record( $test, $result ) {
1157 $this->total++;
1158 $this->success += ($result ? 1 : 0);
1159 }
1160
1161 function end() {
1162 // dummy
1163 }
1164
1165 function report() {
1166 if( $this->total > 0 ) {
1167 $this->reportPercentage( $this->success, $this->total );
1168 } else {
1169 wfDie( "No tests found.\n" );
1170 }
1171 }
1172
1173 function reportPercentage( $success, $total ) {
1174 $ratio = wfPercent( 100 * $success / $total );
1175 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
1176 if( $success == $total ) {
1177 print $this->term->color( 32 ) . "ALL TESTS PASSED!";
1178 } else {
1179 $failed = $total - $success ;
1180 print $this->term->color( 31 ) . "$failed tests failed!";
1181 }
1182 print $this->term->reset() . "\n";
1183 return ($success == $total);
1184 }
1185 }
1186
1187 class DbTestPreviewer extends TestRecorder {
1188 protected $lb; ///< Database load balancer
1189 protected $db; ///< Database connection to the main DB
1190 protected $curRun; ///< run ID number for the current run
1191 protected $prevRun; ///< run ID number for the previous run, if any
1192 protected $results; ///< Result array
1193
1194 /**
1195 * This should be called before the table prefix is changed
1196 */
1197 function __construct( $parent ) {
1198 parent::__construct( $parent );
1199 $this->lb = wfGetLBFactory()->newMainLB();
1200 // This connection will have the wiki's table prefix, not parsertest_
1201 $this->db = $this->lb->getConnection( DB_MASTER );
1202 }
1203
1204 /**
1205 * Set up result recording; insert a record for the run with the date
1206 * and all that fun stuff
1207 */
1208 function start() {
1209 global $wgDBtype, $wgDBprefix;
1210 parent::start();
1211
1212 if( ! $this->db->tableExists( 'testrun' )
1213 or ! $this->db->tableExists( 'testitem' ) )
1214 {
1215 print "WARNING> `testrun` table not found in database.\n";
1216 $this->prevRun = false;
1217 } else {
1218 // We'll make comparisons against the previous run later...
1219 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
1220 }
1221 $this->results = array();
1222 }
1223
1224 function record( $test, $result ) {
1225 parent::record( $test, $result );
1226 $this->results[$test] = $result;
1227 }
1228
1229 function report() {
1230 if( $this->prevRun ) {
1231 // f = fail, p = pass, n = nonexistent
1232 // codes show before then after
1233 $table = array(
1234 'fp' => 'previously failing test(s) now PASSING! :)',
1235 'pn' => 'previously PASSING test(s) removed o_O',
1236 'np' => 'new PASSING test(s) :)',
1237
1238 'pf' => 'previously passing test(s) now FAILING! :(',
1239 'fn' => 'previously FAILING test(s) removed O_o',
1240 'nf' => 'new FAILING test(s) :(',
1241 'ff' => 'still FAILING test(s) :(',
1242 );
1243
1244 $prevResults = array();
1245
1246 $res = $this->db->select( 'testitem', array( 'ti_name', 'ti_success' ),
1247 array( 'ti_run' => $this->prevRun ), __METHOD__ );
1248 foreach ( $res as $row ) {
1249 if ( !$this->parent->regex
1250 || preg_match( "/{$this->parent->regex}/i", $row->ti_name ) )
1251 {
1252 $prevResults[$row->ti_name] = $row->ti_success;
1253 }
1254 }
1255
1256 $combined = array_keys( $this->results + $prevResults );
1257
1258 # Determine breakdown by change type
1259 $breakdown = array();
1260 foreach ( $combined as $test ) {
1261 if ( !isset( $prevResults[$test] ) ) {
1262 $before = 'n';
1263 } elseif ( $prevResults[$test] == 1 ) {
1264 $before = 'p';
1265 } else /* if ( $prevResults[$test] == 0 )*/ {
1266 $before = 'f';
1267 }
1268 if ( !isset( $this->results[$test] ) ) {
1269 $after = 'n';
1270 } elseif ( $this->results[$test] == 1 ) {
1271 $after = 'p';
1272 } else /*if ( $this->results[$test] == 0 ) */ {
1273 $after = 'f';
1274 }
1275 $code = $before . $after;
1276 if ( isset( $table[$code] ) ) {
1277 $breakdown[$code][$test] = $this->getTestStatusInfo( $test, $after );
1278 }
1279 }
1280
1281 # Write out results
1282 foreach ( $table as $code => $label ) {
1283 if( !empty( $breakdown[$code] ) ) {
1284 $count = count($breakdown[$code]);
1285 printf( "\n%4d %s\n", $count, $label );
1286 foreach ($breakdown[$code] as $differing_test_name => $statusInfo) {
1287 print " * $differing_test_name [$statusInfo]\n";
1288 }
1289 }
1290 }
1291 } else {
1292 print "No previous test runs to compare against.\n";
1293 }
1294 print "\n";
1295 parent::report();
1296 }
1297
1298 /**
1299 ** Returns a string giving information about when a test last had a status change.
1300 ** Could help to track down when regressions were introduced, as distinct from tests
1301 ** which have never passed (which are more change requests than regressions).
1302 */
1303 private function getTestStatusInfo($testname, $after) {
1304
1305 // If we're looking at a test that has just been removed, then say when it first appeared.
1306 if ( $after == 'n' ) {
1307 $changedRun = $this->db->selectField ( 'testitem',
1308 'MIN(ti_run)',
1309 array( 'ti_name' => $testname ),
1310 __METHOD__ );
1311 $appear = $this->db->selectRow ( 'testrun',
1312 array( 'tr_date', 'tr_mw_version' ),
1313 array( 'tr_id' => $changedRun ),
1314 __METHOD__ );
1315 return "First recorded appearance: "
1316 . date( "d-M-Y H:i:s", strtotime ( $appear->tr_date ) )
1317 . ", " . $appear->tr_mw_version;
1318 }
1319
1320 // Otherwise, this test has previous recorded results.
1321 // See when this test last had a different result to what we're seeing now.
1322 $conds = array(
1323 'ti_name' => $testname,
1324 'ti_success' => ($after == 'f' ? "1" : "0") );
1325 if ( $this->curRun ) {
1326 $conds[] = "ti_run != " . $this->db->addQuotes ( $this->curRun );
1327 }
1328
1329 $changedRun = $this->db->selectField ( 'testitem', 'MAX(ti_run)', $conds, __METHOD__ );
1330
1331 // If no record of ever having had a different result.
1332 if ( is_null ( $changedRun ) ) {
1333 if ($after == "f") {
1334 return "Has never passed";
1335 } else {
1336 return "Has never failed";
1337 }
1338 }
1339
1340 // Otherwise, we're looking at a test whose status has changed.
1341 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
1342 // In this situation, give as much info as we can as to when it changed status.
1343 $pre = $this->db->selectRow ( 'testrun',
1344 array( 'tr_date', 'tr_mw_version' ),
1345 array( 'tr_id' => $changedRun ),
1346 __METHOD__ );
1347 $post = $this->db->selectRow ( 'testrun',
1348 array( 'tr_date', 'tr_mw_version' ),
1349 array( "tr_id > " . $this->db->addQuotes ( $changedRun) ),
1350 __METHOD__,
1351 array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
1352 );
1353
1354 if ( $post ) {
1355 $postDate = date( "d-M-Y H:i:s", strtotime ( $post->tr_date ) ) . ", {$post->tr_mw_version}";
1356 } else {
1357 $postDate = 'now';
1358 }
1359 return ( $after == "f" ? "Introduced" : "Fixed" ) . " between "
1360 . date( "d-M-Y H:i:s", strtotime ( $pre->tr_date ) ) . ", " . $pre->tr_mw_version
1361 . " and $postDate";
1362
1363 }
1364
1365 /**
1366 * Commit transaction and clean up for result recording
1367 */
1368 function end() {
1369 $this->lb->commitMasterChanges();
1370 $this->lb->closeAll();
1371 parent::end();
1372 }
1373
1374 }
1375
1376 class DbTestRecorder extends DbTestPreviewer {
1377 /**
1378 * Set up result recording; insert a record for the run with the date
1379 * and all that fun stuff
1380 */
1381 function start() {
1382 global $wgDBtype, $wgDBprefix;
1383 $this->db->begin();
1384
1385 if( ! $this->db->tableExists( 'testrun' )
1386 or ! $this->db->tableExists( 'testitem' ) )
1387 {
1388 print "WARNING> `testrun` table not found in database. Trying to create table.\n";
1389 if ($wgDBtype === 'postgres')
1390 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.postgres.sql' );
1391 else
1392 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.sql' );
1393 echo "OK, resuming.\n";
1394 }
1395
1396 parent::start();
1397
1398 $this->db->insert( 'testrun',
1399 array(
1400 'tr_date' => $this->db->timestamp(),
1401 'tr_mw_version' => SpecialVersion::getVersion(),
1402 'tr_php_version' => phpversion(),
1403 'tr_db_version' => $this->db->getServerVersion(),
1404 'tr_uname' => php_uname()
1405 ),
1406 __METHOD__ );
1407 if ($wgDBtype === 'postgres')
1408 $this->curRun = $this->db->currentSequenceValue('testrun_id_seq');
1409 else
1410 $this->curRun = $this->db->insertId();
1411 }
1412
1413 /**
1414 * Record an individual test item's success or failure to the db
1415 * @param string $test
1416 * @param bool $result
1417 */
1418 function record( $test, $result ) {
1419 parent::record( $test, $result );
1420 $this->db->insert( 'testitem',
1421 array(
1422 'ti_run' => $this->curRun,
1423 'ti_name' => $test,
1424 'ti_success' => $result ? 1 : 0,
1425 ),
1426 __METHOD__ );
1427 }
1428 }