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