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