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