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