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