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