fixes #22501 follow up r61101 remove superfluous, buggy code that was over-rideing...
[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 'wgAllowDisplayTitle' => true,
560 'wgRestrictDisplayTitle' => false,
561 );
562
563 if ($config) {
564 $configLines = explode( "\n", $config );
565
566 foreach( $configLines as $line ) {
567 list( $var, $value ) = explode( '=', $line, 2 );
568
569 $settings[$var] = eval("return $value;" );
570 }
571 }
572
573 $this->savedGlobals = array();
574 foreach( $settings as $var => $val ) {
575 if( array_key_exists( $var, $GLOBALS ) ) {
576 $this->savedGlobals[$var] = $GLOBALS[$var];
577 }
578 $GLOBALS[$var] = $val;
579 }
580 $langObj = Language::factory( $lang );
581 $GLOBALS['wgLang'] = $langObj;
582 $GLOBALS['wgContLang'] = $langObj;
583 $GLOBALS['wgMemc'] = new FakeMemCachedClient;
584 $GLOBALS['wgOut'] = new OutputPage;
585
586 MagicWord::clearCache();
587
588 global $wgUser;
589 $wgUser = new User();
590 }
591
592 /**
593 * List of temporary tables to create, without prefix.
594 * Some of these probably aren't necessary.
595 */
596 private function listTables() {
597 global $wgDBtype;
598 $tables = array('user', 'page', 'page_restrictions',
599 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
600 'categorylinks', 'templatelinks', 'externallinks', 'langlinks',
601 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
602 'recentchanges', 'watchlist', 'math', 'interwiki',
603 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
604 'archive', 'user_groups', 'page_props', 'category'
605 );
606
607 if ($wgDBtype === 'mysql')
608 array_push( $tables, 'searchindex' );
609
610 // Allow extensions to add to the list of tables to duplicate;
611 // may be necessary if they hook into page save or other code
612 // which will require them while running tests.
613 wfRunHooks( 'ParserTestTables', array( &$tables ) );
614
615 return $tables;
616 }
617
618 /**
619 * Set up a temporary set of wiki tables to work with for the tests.
620 * Currently this will only be done once per run, and any changes to
621 * the db will be visible to later tests in the run.
622 */
623 function setupDatabase() {
624 global $wgDBprefix, $wgDBtype;
625 if ( $this->databaseSetupDone ) {
626 return;
627 }
628 if ( $wgDBprefix === 'parsertest_' || ($wgDBtype == 'oracle' && $wgDBprefix === 'pt_')) {
629 throw new MWException( 'setupDatabase should be called before setupGlobals' );
630 }
631 $this->databaseSetupDone = true;
632 $this->oldTablePrefix = $wgDBprefix;
633
634 # CREATE TEMPORARY TABLE breaks if there is more than one server
635 # FIXME: r40209 makes temporary tables break even with just one server
636 # FIXME: (bug 15892); disabling the feature entirely as a temporary fix
637 if ( true || wfGetLB()->getServerCount() != 1 ) {
638 $this->useTemporaryTables = false;
639 }
640
641 $temporary = $this->useTemporaryTables || $wgDBtype == 'postgres';
642
643 $db = wfGetDB( DB_MASTER );
644 $tables = $this->listTables();
645
646 foreach ( $tables as $tbl ) {
647 # Clean up from previous aborted run. So that table escaping
648 # works correctly across DB engines, we need to change the pre-
649 # fix back and forth so tableName() works right.
650 $this->changePrefix( $this->oldTablePrefix );
651 $oldTableName = $db->tableName( $tbl );
652 $this->changePrefix( $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_' );
653 $newTableName = $db->tableName( $tbl );
654
655 if ( $db->tableExists( $tbl ) && $wgDBtype != 'postgres' && $wgDBtype != 'oracle' ) {
656 $db->query( "DROP TABLE $newTableName" );
657 }
658 # Create new table
659 $db->duplicateTableStructure( $oldTableName, $newTableName, $temporary );
660 }
661 if ($wgDBtype == 'oracle')
662 $db->query('BEGIN FILL_WIKI_INFO; END;');
663
664 $this->changePrefix( $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_' );
665
666 # Hack: insert a few Wikipedia in-project interwiki prefixes,
667 # for testing inter-language links
668 $db->insert( 'interwiki', array(
669 array( 'iw_prefix' => 'wikipedia',
670 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
671 'iw_local' => 0 ),
672 array( 'iw_prefix' => 'meatball',
673 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
674 'iw_local' => 0 ),
675 array( 'iw_prefix' => 'zh',
676 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
677 'iw_local' => 1 ),
678 array( 'iw_prefix' => 'es',
679 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
680 'iw_local' => 1 ),
681 array( 'iw_prefix' => 'fr',
682 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
683 'iw_local' => 1 ),
684 array( 'iw_prefix' => 'ru',
685 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
686 'iw_local' => 1 ),
687 ) );
688
689
690 if ($wgDBtype == 'oracle') {
691 # Insert 0 and 1 user_ids to prevent FK violations
692
693 #Anonymous user
694 $db->insert( 'user', array(
695 'user_id' => 0,
696 'user_name' => 'Anonymous') );
697
698 # Hack-on-Hack: Insert a test user to be able to insert an image
699 $db->insert( 'user', array(
700 'user_id' => 1,
701 'user_name' => 'Tester') );
702 }
703
704 # Hack: Insert an image to work with
705 $db->insert( 'image', array(
706 'img_name' => 'Foobar.jpg',
707 'img_size' => 12345,
708 'img_description' => 'Some lame file',
709 'img_user' => 1,
710 'img_user_text' => 'WikiSysop',
711 'img_timestamp' => $db->timestamp( '20010115123500' ),
712 'img_width' => 1941,
713 'img_height' => 220,
714 'img_bits' => 24,
715 'img_media_type' => MEDIATYPE_BITMAP,
716 'img_major_mime' => "image",
717 'img_minor_mime' => "jpeg",
718 'img_metadata' => serialize( array() ),
719 ) );
720
721 # This image will be blacklisted in [[MediaWiki:Bad image list]]
722 $db->insert( 'image', array(
723 'img_name' => 'Bad.jpg',
724 'img_size' => 12345,
725 'img_description' => 'zomgnotcensored',
726 'img_user' => 1,
727 'img_user_text' => 'WikiSysop',
728 'img_timestamp' => $db->timestamp( '20010115123500' ),
729 'img_width' => 320,
730 'img_height' => 240,
731 'img_bits' => 24,
732 'img_media_type' => MEDIATYPE_BITMAP,
733 'img_major_mime' => "image",
734 'img_minor_mime' => "jpeg",
735 'img_metadata' => serialize( array() ),
736 ) );
737
738 # Update certain things in site_stats
739 $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
740
741 # Reinitialise the LocalisationCache to match the database state
742 Language::getLocalisationCache()->unloadAll();
743
744 # Make a new message cache
745 global $wgMessageCache, $wgMemc;
746 $wgMessageCache = new MessageCache( $wgMemc, true, 3600, '' );
747 }
748
749 /**
750 * Change the table prefix on all open DB connections/
751 */
752 protected function changePrefix( $prefix ) {
753 global $wgDBprefix;
754 wfGetLBFactory()->forEachLB( array( $this, 'changeLBPrefix' ), array( $prefix ) );
755 $wgDBprefix = $prefix;
756 }
757
758 public function changeLBPrefix( $lb, $prefix ) {
759 $lb->forEachOpenConnection( array( $this, 'changeDBPrefix' ), array( $prefix ) );
760 }
761
762 public function changeDBPrefix( $db, $prefix ) {
763 $db->tablePrefix( $prefix );
764 }
765
766 private function teardownDatabase() {
767 global $wgDBprefix, $wgDBtype;
768 if ( !$this->databaseSetupDone ) {
769 return;
770 }
771 $this->changePrefix( $this->oldTablePrefix );
772 $this->databaseSetupDone = false;
773 if ( $this->useTemporaryTables ) {
774 # Don't need to do anything
775 return;
776 }
777
778 /*
779 $tables = $this->listTables();
780 $db = wfGetDB( DB_MASTER );
781 foreach ( $tables as $table ) {
782 $sql = $wgDBtype == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
783 $db->query( $sql );
784 }
785 if ($wgDBtype == 'oracle')
786 $db->query('BEGIN FILL_WIKI_INFO; END;');
787 */
788 }
789
790 /**
791 * Create a dummy uploads directory which will contain a couple
792 * of files in order to pass existence tests.
793 * @return string The directory
794 */
795 private function setupUploadDir() {
796 global $IP;
797 if ( $this->keepUploads ) {
798 $dir = wfTempDir() . '/mwParser-images';
799 if ( is_dir( $dir ) ) {
800 return $dir;
801 }
802 } else {
803 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
804 }
805
806 wfDebug( "Creating upload directory $dir\n" );
807 if ( file_exists( $dir ) ) {
808 wfDebug( "Already exists!\n" );
809 return $dir;
810 }
811 wfMkdirParents( $dir . '/3/3a' );
812 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
813
814 wfMkdirParents( $dir . '/0/09' );
815 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
816 return $dir;
817 }
818
819 /**
820 * Restore default values and perform any necessary clean-up
821 * after each test runs.
822 */
823 private function teardownGlobals() {
824 RepoGroup::destroySingleton();
825 LinkCache::singleton()->clear();
826 foreach( $this->savedGlobals as $var => $val ) {
827 $GLOBALS[$var] = $val;
828 }
829 if( isset( $this->uploadDir ) ) {
830 $this->teardownUploadDir( $this->uploadDir );
831 unset( $this->uploadDir );
832 }
833 }
834
835 /**
836 * Remove the dummy uploads directory
837 */
838 private function teardownUploadDir( $dir ) {
839 if ( $this->keepUploads ) {
840 return;
841 }
842
843 // delete the files first, then the dirs.
844 self::deleteFiles(
845 array (
846 "$dir/3/3a/Foobar.jpg",
847 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
848 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
849 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
850 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
851
852 "$dir/0/09/Bad.jpg",
853
854 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
855 )
856 );
857
858 self::deleteDirs(
859 array (
860 "$dir/3/3a",
861 "$dir/3",
862 "$dir/thumb/6/65",
863 "$dir/thumb/6",
864 "$dir/thumb/3/3a/Foobar.jpg",
865 "$dir/thumb/3/3a",
866 "$dir/thumb/3",
867
868 "$dir/0/09/",
869 "$dir/0/",
870 "$dir/thumb",
871 "$dir/math/f/a/5",
872 "$dir/math/f/a",
873 "$dir/math/f",
874 "$dir/math",
875 "$dir",
876 )
877 );
878 }
879
880 /**
881 * Delete the specified files, if they exist.
882 * @param array $files full paths to files to delete.
883 */
884 private static function deleteFiles( $files ) {
885 foreach( $files as $file ) {
886 if( file_exists( $file ) ) {
887 unlink( $file );
888 }
889 }
890 }
891
892 /**
893 * Delete the specified directories, if they exist. Must be empty.
894 * @param array $dirs full paths to directories to delete.
895 */
896 private static function deleteDirs( $dirs ) {
897 foreach( $dirs as $dir ) {
898 if( is_dir( $dir ) ) {
899 rmdir( $dir );
900 }
901 }
902 }
903
904 /**
905 * "Running test $desc..."
906 */
907 protected function showTesting( $desc ) {
908 print "Running test $desc... ";
909 }
910
911 /**
912 * Print a happy success message.
913 *
914 * @param string $desc The test name
915 * @return bool
916 */
917 protected function showSuccess( $desc ) {
918 if( $this->showProgress ) {
919 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
920 }
921 return true;
922 }
923
924 /**
925 * Print a failure message and provide some explanatory output
926 * about what went wrong if so configured.
927 *
928 * @param string $desc The test name
929 * @param string $result Expected HTML output
930 * @param string $html Actual HTML output
931 * @return bool
932 */
933 protected function showFailure( $desc, $result, $html ) {
934 if( $this->showFailure ) {
935 if( !$this->showProgress ) {
936 # In quiet mode we didn't show the 'Testing' message before the
937 # test, in case it succeeded. Show it now:
938 $this->showTesting( $desc );
939 }
940 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
941 if ( $this->showOutput ) {
942 print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
943 }
944 if( $this->showDiffs ) {
945 print $this->quickDiff( $result, $html );
946 if( !$this->wellFormed( $html ) ) {
947 print "XML error: $this->mXmlError\n";
948 }
949 }
950 }
951 return false;
952 }
953
954 /**
955 * Run given strings through a diff and return the (colorized) output.
956 * Requires writable /tmp directory and a 'diff' command in the PATH.
957 *
958 * @param string $input
959 * @param string $output
960 * @param string $inFileTail Tailing for the input file name
961 * @param string $outFileTail Tailing for the output file name
962 * @return string
963 */
964 protected function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
965 $prefix = wfTempDir() . "/mwParser-" . mt_rand();
966
967 $infile = "$prefix-$inFileTail";
968 $this->dumpToFile( $input, $infile );
969
970 $outfile = "$prefix-$outFileTail";
971 $this->dumpToFile( $output, $outfile );
972
973 $diff = `diff -au $infile $outfile`;
974 unlink( $infile );
975 unlink( $outfile );
976
977 return $this->colorDiff( $diff );
978 }
979
980 /**
981 * Write the given string to a file, adding a final newline.
982 *
983 * @param string $data
984 * @param string $filename
985 */
986 private function dumpToFile( $data, $filename ) {
987 $file = fopen( $filename, "wt" );
988 fwrite( $file, $data . "\n" );
989 fclose( $file );
990 }
991
992 /**
993 * Colorize unified diff output if set for ANSI color output.
994 * Subtractions are colored blue, additions red.
995 *
996 * @param string $text
997 * @return string
998 */
999 protected function colorDiff( $text ) {
1000 return preg_replace(
1001 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1002 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1003 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1004 $text );
1005 }
1006
1007 /**
1008 * Show "Reading tests from ..."
1009 *
1010 * @param String $path
1011 */
1012 public function showRunFile( $path ){
1013 print $this->term->color( 1 ) .
1014 "Reading tests from \"$path\"..." .
1015 $this->term->reset() .
1016 "\n";
1017 }
1018
1019 /**
1020 * Insert a temporary test article
1021 * @param string $name the title, including any prefix
1022 * @param string $text the article text
1023 * @param int $line the input line number, for reporting errors
1024 */
1025 public function addArticle($name, $text, $line) {
1026 $this->setupGlobals();
1027 $title = Title::newFromText( $name );
1028 if ( is_null($title) ) {
1029 wfDie( "invalid title at line $line\n" );
1030 }
1031
1032 $aid = $title->getArticleID( GAID_FOR_UPDATE );
1033 if ($aid != 0) {
1034 wfDie( "duplicate article '$name' at line $line\n" );
1035 }
1036
1037 $art = new Article($title);
1038 $art->insertNewArticle($text, '', false, false );
1039
1040 $this->teardownGlobals();
1041 }
1042
1043 /**
1044 * Steal a callback function from the primary parser, save it for
1045 * application to our scary parser. If the hook is not installed,
1046 * die a painful dead to warn the others.
1047 * @param string $name
1048 */
1049 public function requireHook( $name ) {
1050 global $wgParser;
1051 $wgParser->firstCallInit( ); //make sure hooks are loaded.
1052 if( isset( $wgParser->mTagHooks[$name] ) ) {
1053 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1054 } else {
1055 wfDie( "This test suite requires the '$name' hook extension.\n" );
1056 }
1057 }
1058
1059 /**
1060 * Steal a callback function from the primary parser, save it for
1061 * application to our scary parser. If the hook is not installed,
1062 * die a painful dead to warn the others.
1063 * @param string $name
1064 */
1065 private function requireFunctionHook( $name ) {
1066 global $wgParser;
1067 $wgParser->firstCallInit( ); //make sure hooks are loaded.
1068 if( isset( $wgParser->mFunctionHooks[$name] ) ) {
1069 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1070 } else {
1071 wfDie( "This test suite requires the '$name' function hook extension.\n" );
1072 }
1073 }
1074
1075 /*
1076 * Run the "tidy" command on text if the $wgUseTidy
1077 * global is true
1078 *
1079 * @param string $text the text to tidy
1080 * @return string
1081 * @static
1082 */
1083 private function tidy( $text ) {
1084 global $wgUseTidy;
1085 if ($wgUseTidy) {
1086 $text = Parser::tidy($text);
1087 }
1088 return $text;
1089 }
1090
1091 private function wellFormed( $text ) {
1092 $html =
1093 Sanitizer::hackDocType() .
1094 '<html>' .
1095 $text .
1096 '</html>';
1097
1098 $parser = xml_parser_create( "UTF-8" );
1099
1100 # case folding violates XML standard, turn it off
1101 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1102
1103 if( !xml_parse( $parser, $html, true ) ) {
1104 $err = xml_error_string( xml_get_error_code( $parser ) );
1105 $position = xml_get_current_byte_index( $parser );
1106 $fragment = $this->extractFragment( $html, $position );
1107 $this->mXmlError = "$err at byte $position:\n$fragment";
1108 xml_parser_free( $parser );
1109 return false;
1110 }
1111 xml_parser_free( $parser );
1112 return true;
1113 }
1114
1115 private function extractFragment( $text, $position ) {
1116 $start = max( 0, $position - 10 );
1117 $before = $position - $start;
1118 $fragment = '...' .
1119 $this->term->color( 34 ) .
1120 substr( $text, $start, $before ) .
1121 $this->term->color( 0 ) .
1122 $this->term->color( 31 ) .
1123 $this->term->color( 1 ) .
1124 substr( $text, $position, 1 ) .
1125 $this->term->color( 0 ) .
1126 $this->term->color( 34 ) .
1127 substr( $text, $position + 1, 9 ) .
1128 $this->term->color( 0 ) .
1129 '...';
1130 $display = str_replace( "\n", ' ', $fragment );
1131 $caret = ' ' .
1132 str_repeat( ' ', $before ) .
1133 $this->term->color( 31 ) .
1134 '^' .
1135 $this->term->color( 0 );
1136 return "$display\n$caret";
1137 }
1138 }
1139
1140 class AnsiTermColorer {
1141 function __construct() {
1142 }
1143
1144 /**
1145 * Return ANSI terminal escape code for changing text attribs/color
1146 *
1147 * @param string $color Semicolon-separated list of attribute/color codes
1148 * @return string
1149 */
1150 public function color( $color ) {
1151 global $wgCommandLineDarkBg;
1152 $light = $wgCommandLineDarkBg ? "1;" : "0;";
1153 return "\x1b[{$light}{$color}m";
1154 }
1155
1156 /**
1157 * Return ANSI terminal escape code for restoring default text attributes
1158 *
1159 * @return string
1160 */
1161 public function reset() {
1162 return $this->color( 0 );
1163 }
1164 }
1165
1166 /* A colour-less terminal */
1167 class DummyTermColorer {
1168 public function color( $color ) {
1169 return '';
1170 }
1171
1172 public function reset() {
1173 return '';
1174 }
1175 }
1176
1177 class TestRecorder {
1178 var $parent;
1179 var $term;
1180
1181 function __construct( $parent ) {
1182 $this->parent = $parent;
1183 $this->term = $parent->term;
1184 }
1185
1186 function start() {
1187 $this->total = 0;
1188 $this->success = 0;
1189 }
1190
1191 function record( $test, $result ) {
1192 $this->total++;
1193 $this->success += ($result ? 1 : 0);
1194 }
1195
1196 function end() {
1197 // dummy
1198 }
1199
1200 function report() {
1201 if( $this->total > 0 ) {
1202 $this->reportPercentage( $this->success, $this->total );
1203 } else {
1204 wfDie( "No tests found.\n" );
1205 }
1206 }
1207
1208 function reportPercentage( $success, $total ) {
1209 $ratio = wfPercent( 100 * $success / $total );
1210 print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
1211 if( $success == $total ) {
1212 print $this->term->color( 32 ) . "ALL TESTS PASSED!";
1213 } else {
1214 $failed = $total - $success ;
1215 print $this->term->color( 31 ) . "$failed tests failed!";
1216 }
1217 print $this->term->reset() . "\n";
1218 return ($success == $total);
1219 }
1220 }
1221
1222 class DbTestPreviewer extends TestRecorder {
1223 protected $lb; ///< Database load balancer
1224 protected $db; ///< Database connection to the main DB
1225 protected $curRun; ///< run ID number for the current run
1226 protected $prevRun; ///< run ID number for the previous run, if any
1227 protected $results; ///< Result array
1228
1229 /**
1230 * This should be called before the table prefix is changed
1231 */
1232 function __construct( $parent ) {
1233 parent::__construct( $parent );
1234 $this->lb = wfGetLBFactory()->newMainLB();
1235 // This connection will have the wiki's table prefix, not parsertest_
1236 $this->db = $this->lb->getConnection( DB_MASTER );
1237 }
1238
1239 /**
1240 * Set up result recording; insert a record for the run with the date
1241 * and all that fun stuff
1242 */
1243 function start() {
1244 global $wgDBtype, $wgDBprefix;
1245 parent::start();
1246
1247 if( ! $this->db->tableExists( 'testrun' )
1248 or ! $this->db->tableExists( 'testitem' ) )
1249 {
1250 print "WARNING> `testrun` table not found in database.\n";
1251 $this->prevRun = false;
1252 } else {
1253 // We'll make comparisons against the previous run later...
1254 $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
1255 }
1256 $this->results = array();
1257 }
1258
1259 function record( $test, $result ) {
1260 parent::record( $test, $result );
1261 $this->results[$test] = $result;
1262 }
1263
1264 function report() {
1265 if( $this->prevRun ) {
1266 // f = fail, p = pass, n = nonexistent
1267 // codes show before then after
1268 $table = array(
1269 'fp' => 'previously failing test(s) now PASSING! :)',
1270 'pn' => 'previously PASSING test(s) removed o_O',
1271 'np' => 'new PASSING test(s) :)',
1272
1273 'pf' => 'previously passing test(s) now FAILING! :(',
1274 'fn' => 'previously FAILING test(s) removed O_o',
1275 'nf' => 'new FAILING test(s) :(',
1276 'ff' => 'still FAILING test(s) :(',
1277 );
1278
1279 $prevResults = array();
1280
1281 $res = $this->db->select( 'testitem', array( 'ti_name', 'ti_success' ),
1282 array( 'ti_run' => $this->prevRun ), __METHOD__ );
1283 foreach ( $res as $row ) {
1284 if ( !$this->parent->regex
1285 || preg_match( "/{$this->parent->regex}/i", $row->ti_name ) )
1286 {
1287 $prevResults[$row->ti_name] = $row->ti_success;
1288 }
1289 }
1290
1291 $combined = array_keys( $this->results + $prevResults );
1292
1293 # Determine breakdown by change type
1294 $breakdown = array();
1295 foreach ( $combined as $test ) {
1296 if ( !isset( $prevResults[$test] ) ) {
1297 $before = 'n';
1298 } elseif ( $prevResults[$test] == 1 ) {
1299 $before = 'p';
1300 } else /* if ( $prevResults[$test] == 0 )*/ {
1301 $before = 'f';
1302 }
1303 if ( !isset( $this->results[$test] ) ) {
1304 $after = 'n';
1305 } elseif ( $this->results[$test] == 1 ) {
1306 $after = 'p';
1307 } else /*if ( $this->results[$test] == 0 ) */ {
1308 $after = 'f';
1309 }
1310 $code = $before . $after;
1311 if ( isset( $table[$code] ) ) {
1312 $breakdown[$code][$test] = $this->getTestStatusInfo( $test, $after );
1313 }
1314 }
1315
1316 # Write out results
1317 foreach ( $table as $code => $label ) {
1318 if( !empty( $breakdown[$code] ) ) {
1319 $count = count($breakdown[$code]);
1320 printf( "\n%4d %s\n", $count, $label );
1321 foreach ($breakdown[$code] as $differing_test_name => $statusInfo) {
1322 print " * $differing_test_name [$statusInfo]\n";
1323 }
1324 }
1325 }
1326 } else {
1327 print "No previous test runs to compare against.\n";
1328 }
1329 print "\n";
1330 parent::report();
1331 }
1332
1333 /**
1334 ** Returns a string giving information about when a test last had a status change.
1335 ** Could help to track down when regressions were introduced, as distinct from tests
1336 ** which have never passed (which are more change requests than regressions).
1337 */
1338 private function getTestStatusInfo($testname, $after) {
1339
1340 // If we're looking at a test that has just been removed, then say when it first appeared.
1341 if ( $after == 'n' ) {
1342 $changedRun = $this->db->selectField ( 'testitem',
1343 'MIN(ti_run)',
1344 array( 'ti_name' => $testname ),
1345 __METHOD__ );
1346 $appear = $this->db->selectRow ( 'testrun',
1347 array( 'tr_date', 'tr_mw_version' ),
1348 array( 'tr_id' => $changedRun ),
1349 __METHOD__ );
1350 return "First recorded appearance: "
1351 . date( "d-M-Y H:i:s", strtotime ( $appear->tr_date ) )
1352 . ", " . $appear->tr_mw_version;
1353 }
1354
1355 // Otherwise, this test has previous recorded results.
1356 // See when this test last had a different result to what we're seeing now.
1357 $conds = array(
1358 'ti_name' => $testname,
1359 'ti_success' => ($after == 'f' ? "1" : "0") );
1360 if ( $this->curRun ) {
1361 $conds[] = "ti_run != " . $this->db->addQuotes ( $this->curRun );
1362 }
1363
1364 $changedRun = $this->db->selectField ( 'testitem', 'MAX(ti_run)', $conds, __METHOD__ );
1365
1366 // If no record of ever having had a different result.
1367 if ( is_null ( $changedRun ) ) {
1368 if ($after == "f") {
1369 return "Has never passed";
1370 } else {
1371 return "Has never failed";
1372 }
1373 }
1374
1375 // Otherwise, we're looking at a test whose status has changed.
1376 // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
1377 // In this situation, give as much info as we can as to when it changed status.
1378 $pre = $this->db->selectRow ( 'testrun',
1379 array( 'tr_date', 'tr_mw_version' ),
1380 array( 'tr_id' => $changedRun ),
1381 __METHOD__ );
1382 $post = $this->db->selectRow ( 'testrun',
1383 array( 'tr_date', 'tr_mw_version' ),
1384 array( "tr_id > " . $this->db->addQuotes ( $changedRun) ),
1385 __METHOD__,
1386 array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
1387 );
1388
1389 if ( $post ) {
1390 $postDate = date( "d-M-Y H:i:s", strtotime ( $post->tr_date ) ) . ", {$post->tr_mw_version}";
1391 } else {
1392 $postDate = 'now';
1393 }
1394 return ( $after == "f" ? "Introduced" : "Fixed" ) . " between "
1395 . date( "d-M-Y H:i:s", strtotime ( $pre->tr_date ) ) . ", " . $pre->tr_mw_version
1396 . " and $postDate";
1397
1398 }
1399
1400 /**
1401 * Commit transaction and clean up for result recording
1402 */
1403 function end() {
1404 $this->lb->commitMasterChanges();
1405 $this->lb->closeAll();
1406 parent::end();
1407 }
1408
1409 }
1410
1411 class DbTestRecorder extends DbTestPreviewer {
1412 /**
1413 * Set up result recording; insert a record for the run with the date
1414 * and all that fun stuff
1415 */
1416 function start() {
1417 global $wgDBtype, $wgDBprefix, $options;
1418 $this->db->begin();
1419
1420 if( ! $this->db->tableExists( 'testrun' )
1421 or ! $this->db->tableExists( 'testitem' ) )
1422 {
1423 print "WARNING> `testrun` table not found in database. Trying to create table.\n";
1424 if ($wgDBtype === 'postgres')
1425 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.postgres.sql' );
1426 elseif ($wgDBtype === 'oracle')
1427 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.ora.sql' );
1428 else
1429 $this->db->sourceFile( dirname(__FILE__) . '/testRunner.sql' );
1430 echo "OK, resuming.\n";
1431 }
1432
1433 parent::start();
1434
1435 $this->db->insert( 'testrun',
1436 array(
1437 'tr_date' => $this->db->timestamp(),
1438 'tr_mw_version' => isset( $options['setversion'] ) ?
1439 $options['setversion'] : SpecialVersion::getVersion(),
1440 'tr_php_version' => phpversion(),
1441 'tr_db_version' => $this->db->getServerVersion(),
1442 'tr_uname' => php_uname()
1443 ),
1444 __METHOD__ );
1445 if ($wgDBtype === 'postgres')
1446 $this->curRun = $this->db->currentSequenceValue('testrun_id_seq');
1447 else
1448 $this->curRun = $this->db->insertId();
1449 }
1450
1451 /**
1452 * Record an individual test item's success or failure to the db
1453 * @param string $test
1454 * @param bool $result
1455 */
1456 function record( $test, $result ) {
1457 parent::record( $test, $result );
1458 $this->db->insert( 'testitem',
1459 array(
1460 'ti_run' => $this->curRun,
1461 'ti_name' => $test,
1462 'ti_success' => $result ? 1 : 0,
1463 ),
1464 __METHOD__ );
1465 }
1466 }
1467
1468 class RemoteTestRecorder extends TestRecorder {
1469 function start() {
1470 parent::start();
1471 $this->results = array();
1472 $this->ping( 'running' );
1473 }
1474
1475 function record( $test, $result ) {
1476 parent::record( $test, $result );
1477 $this->results[$test] = (bool)$result;
1478 }
1479
1480 function end() {
1481 $this->ping( 'complete', $this->results );
1482 parent::end();
1483 }
1484
1485 /**
1486 * Inform a CodeReview instance that we've started or completed a test run...
1487 * @param $remote array: info on remote target
1488 * @param $status string: "running" - tell it we've started
1489 * "complete" - provide test results array
1490 * "abort" - something went horribly awry
1491 * @param $data array of test name => true/false
1492 */
1493 function ping( $status, $results=false ) {
1494 global $wgParserTestRemote, $IP;
1495
1496 $remote = $wgParserTestRemote;
1497 $revId = SpecialVersion::getSvnRevision( $IP );
1498 $jsonResults = json_encode( $results );
1499
1500 if( !$remote ) {
1501 print "Can't do remote upload without configuring \$wgParserTestRemote!\n";
1502 exit( 1 );
1503 }
1504
1505 // Generate a hash MAC to validate our credentials
1506 $message = array(
1507 $remote['repo'],
1508 $remote['suite'],
1509 $revId,
1510 $status,
1511 );
1512 if( $status == "complete" ) {
1513 $message[] = $jsonResults;
1514 }
1515 $hmac = hash_hmac( "sha1", implode( "|", $message ), $remote['secret'] );
1516
1517 $postData = array(
1518 'action' => 'codetestupload',
1519 'format' => 'json',
1520 'repo' => $remote['repo'],
1521 'suite' => $remote['suite'],
1522 'rev' => $revId,
1523 'status' => $status,
1524 'hmac' => $hmac,
1525 );
1526 if( $status == "complete" ) {
1527 $postData['results'] = $jsonResults;
1528 }
1529 $response = $this->post( $remote['api-url'], $postData );
1530
1531 if( $response === false ) {
1532 print "CodeReview info upload failed to reach server.\n";
1533 exit( 1 );
1534 }
1535 $responseData = json_decode( $response, true );
1536 if( !is_array( $responseData ) ) {
1537 print "CodeReview API response not recognized...\n";
1538 wfDebug( "Unrecognized CodeReview API response: $response\n" );
1539 exit( 1 );
1540 }
1541 if( isset( $responseData['error'] ) ) {
1542 $code = $responseData['error']['code'];
1543 $info = $responseData['error']['info'];
1544 print "CodeReview info upload failed: $code $info\n";
1545 exit( 1 );
1546 }
1547 }
1548
1549 function post( $url, $data ) {
1550 return Http::post( $url, array( 'postData' => $data) );
1551 }
1552 }
1553
1554 class TestFileIterator implements Iterator {
1555 private $file;
1556 private $fh;
1557 private $parser;
1558 private $index = 0;
1559 private $test;
1560 private $lineNum;
1561 private $eof;
1562
1563 function __construct( $file, $parser = null ) {
1564 global $IP;
1565
1566 $this->file = $file;
1567 $this->fh = fopen($this->file, "rt");
1568 if( !$this->fh ) {
1569 wfDie( "Couldn't open file '$file'\n" );
1570 }
1571
1572 $this->parser = $parser;
1573
1574 if( $this->parser ) $this->parser->showRunFile( wfRelativePath( $this->file, $IP ) );
1575 $this->lineNum = $this->index = 0;
1576 }
1577
1578 function setParser( ParserTest $parser ) {
1579 $this->parser = $parser;
1580 }
1581
1582 function rewind() {
1583 if(fseek($this->fh, 0)) {
1584 wfDie( "Couldn't fseek to the start of '$filename'\n" );
1585 }
1586 $this->index = 0;
1587 $this->lineNum = 0;
1588 $this->eof = false;
1589 $this->readNextTest();
1590
1591 return true;
1592 }
1593
1594 function current() {
1595 return $this->test;
1596 }
1597
1598 function key() {
1599 return $this->index;
1600 }
1601
1602 function next() {
1603 if($this->readNextTest()) {
1604 $this->index++;
1605 return true;
1606 } else {
1607 $this->eof = true;
1608 }
1609 }
1610
1611 function valid() {
1612 return $this->eof != true;
1613 }
1614
1615 function readNextTest() {
1616 $data = array();
1617 $section = null;
1618
1619 while( false !== ($line = fgets( $this->fh ) ) ) {
1620 $this->lineNum++;
1621 $matches = array();
1622 if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
1623 $section = strtolower( $matches[1] );
1624 if( $section == 'endarticle') {
1625 if( !isset( $data['text'] ) ) {
1626 wfDie( "'endarticle' without 'text' at line {$this->lineNum} of $filename\n" );
1627 }
1628 if( !isset( $data['article'] ) ) {
1629 wfDie( "'endarticle' without 'article' at line {$this->lineNum} of $filename\n" );
1630 }
1631 if( $this->parser ) $this->parser->addArticle($this->parser->chomp($data['article']), $this->parser->chomp($data['text']),
1632 $this->lineNum);
1633 $data = array();
1634 $section = null;
1635 continue;
1636 }
1637 if( $section == 'endhooks' ) {
1638 if( !isset( $data['hooks'] ) ) {
1639 wfDie( "'endhooks' without 'hooks' at line {$this->lineNum} of $filename\n" );
1640 }
1641 foreach( explode( "\n", $data['hooks'] ) as $line ) {
1642 $line = trim( $line );
1643 if( $line ) {
1644 if( $this->parser ) $this->parser->requireHook( $line );
1645 }
1646 }
1647 $data = array();
1648 $section = null;
1649 continue;
1650 }
1651 if( $section == 'endfunctionhooks' ) {
1652 if( !isset( $data['functionhooks'] ) ) {
1653 wfDie( "'endfunctionhooks' without 'functionhooks' at line {$this->lineNum} of $filename\n" );
1654 }
1655 foreach( explode( "\n", $data['functionhooks'] ) as $line ) {
1656 $line = trim( $line );
1657 if( $line ) {
1658 if( $this->parser ) $this->parser->requireFunctionHook( $line );
1659 }
1660 }
1661 $data = array();
1662 $section = null;
1663 continue;
1664 }
1665 if( $section == 'end' ) {
1666 if( !isset( $data['test'] ) ) {
1667 wfDie( "'end' without 'test' at line {$this->lineNum} of $filename\n" );
1668 }
1669 if( !isset( $data['input'] ) ) {
1670 wfDie( "'end' without 'input' at line {$this->lineNum} of $filename\n" );
1671 }
1672 if( !isset( $data['result'] ) ) {
1673 wfDie( "'end' without 'result' at line {$this->lineNum} of $filename\n" );
1674 }
1675 if( !isset( $data['options'] ) ) {
1676 $data['options'] = '';
1677 }
1678 if (!isset( $data['config'] ) )
1679 $data['config'] = '';
1680
1681 if ( $this->parser && (preg_match('/\\bdisabled\\b/i', $data['options'])
1682 || !preg_match("/{$this->parser->regex}/i", $data['test'])) && !$this->parser->runDisabled ) {
1683 # disabled test
1684 $data = array();
1685 $section = null;
1686 continue;
1687 }
1688 if ( $this->parser &&
1689 preg_match('/\\bmath\\b/i', $data['options']) && !$this->parser->savedGlobals['wgUseTeX'] ) {
1690 # don't run math tests if $wgUseTeX is set to false in LocalSettings
1691 $data = array();
1692 $section = null;
1693 continue;
1694 }
1695
1696 if( $this->parser ) {
1697 $this->test = array(
1698 'test' => $this->parser->chomp( $data['test'] ),
1699 'input' => $this->parser->chomp( $data['input'] ),
1700 'result' => $this->parser->chomp( $data['result'] ),
1701 'options' => $this->parser->chomp( $data['options'] ),
1702 'config' => $this->parser->chomp( $data['config'] ) );
1703 } else {
1704 $this->test['test'] = $data['test'];
1705 }
1706 return true;
1707 }
1708 if ( isset ($data[$section] ) ) {
1709 wfDie( "duplicate section '$section' at line {$this->lineNum} of $filename\n" );
1710 }
1711 $data[$section] = '';
1712 continue;
1713 }
1714 if( $section ) {
1715 $data[$section] .= $line;
1716 }
1717 }
1718 return false;
1719 }
1720 }