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