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