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