Fixed user scripts/styles and site scripts/styles - they were totally broken in r7277...
[lhc/web/wiklou.git] / maintenance / parserTests.inc
index c34d6d5..896d631 100644 (file)
  * @ingroup Maintenance
  */
 
-/** */
-$options = array( 'quick', 'color', 'quiet', 'help', 'show-output', 'record', 'run-disabled' );
-$optionsWithArgs = array( 'regex', 'seed', 'setversion' );
-
-if ( !defined( "NO_COMMAND_LINE" ) ) {
-       require_once( dirname( __FILE__ ) . '/commandLine.inc' );
-}
-require_once( "$IP/maintenance/parserTestsParserHook.php" );
-require_once( "$IP/maintenance/parserTestsStaticParserHook.php" );
-require_once( "$IP/maintenance/parserTestsParserTime.php" );
-
 /**
  * @ingroup Maintenance
  */
@@ -72,9 +61,7 @@ class ParserTest {
         * Sets terminal colorization and diff/quick modes depending on OS and
         * command-line options (--color and --quick).
         */
-       public function ParserTest() {
-               global $options;
-
+       public function ParserTest( $options = array() ) {
                # Only colorize output if stdout is a terminal.
                $this->color = !wfIsWindows() && posix_isatty( 1 );
 
@@ -89,6 +76,7 @@ class ParserTest {
                                break;
                        }
                }
+
                $this->term = $this->color
                        ? new AnsiTermColorer()
                        : new DummyTermColorer();
@@ -114,17 +102,7 @@ class ParserTest {
                        $this->regex = '';
                }
 
-               if ( isset( $options['record'] ) ) {
-                       $this->recorder = new DbTestRecorder( $this );
-               } elseif ( isset( $options['compare'] ) ) {
-                       $this->recorder = new DbTestPreviewer( $this );
-               } elseif ( isset( $options['upload'] ) ) {
-                       $this->recorder = new RemoteTestRecorder( $this );
-               } elseif ( class_exists( 'PHPUnitTestRecorder' ) ) {
-                       $this->recorder = new PHPUnitTestRecorder( $this );
-               } else {
-                       $this->recorder = new TestRecorder( $this );
-               }
+               $this->setupRecorder( $options );
                $this->keepUploads = isset( $options['keep-uploads'] );
 
                if ( isset( $options['seed'] ) ) {
@@ -137,6 +115,20 @@ class ParserTest {
                $this->functionHooks = array();
        }
 
+       public function setupRecorder ( $options ) {
+               if ( isset( $options['record'] ) ) {
+                       $this->recorder = new DbTestRecorder( $this );
+                       $this->recorder->version = isset( $options['setversion'] ) ?
+                                       $options['setversion'] : SpecialVersion::getVersion();
+               } elseif ( isset( $options['compare'] ) ) {
+                       $this->recorder = new DbTestPreviewer( $this );
+               } elseif ( isset( $options['upload'] ) ) {
+                       $this->recorder = new RemoteTestRecorder( $this );
+               } else {
+                       $this->recorder = new TestRecorder( $this );
+               }
+       }
+
        /**
         * Remove last character if it is a newline
         */
@@ -154,6 +146,7 @@ class ParserTest {
         * Draw input from a set of test files
         */
        function fuzzTest( $filenames ) {
+               $GLOBALS['wgContLang'] = Language::factory( 'en' );
                $dict = $this->getFuzzInput( $filenames );
                $dictSize = strlen( $dict );
                $logMaxLength = log( $this->maxFuzzTestLength );
@@ -171,6 +164,7 @@ class ParserTest {
                        mt_srand( ++$this->fuzzSeed );
                        $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
                        $input = '';
+
                        while ( strlen( $input ) < $totalLength ) {
                                $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
                                $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
@@ -180,6 +174,7 @@ class ParserTest {
 
                        $this->setupGlobals();
                        $parser = $this->getParser();
+
                        // Run the test
                        try {
                                $parser->parse( $input, $title, $opts );
@@ -197,6 +192,7 @@ class ParserTest {
                        } else {
                                $numSuccess++;
                        }
+
                        $numTotal++;
                        $this->teardownGlobals();
                        $parser->__destruct();
@@ -207,6 +203,7 @@ class ParserTest {
                                if ( $usage > 90 ) {
                                        echo "Out of memory:\n";
                                        $memStats = $this->getMemoryBreakdown();
+
                                        foreach ( $memStats as $name => $usage ) {
                                                echo "$name: $usage\n";
                                        }
@@ -221,13 +218,16 @@ class ParserTest {
         */
        function getFuzzInput( $filenames ) {
                $dict = '';
+
                foreach ( $filenames as $filename ) {
                        $contents = file_get_contents( $filename );
                        preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
+
                        foreach ( $matches[1] as $match ) {
                                $dict .= $match . "\n";
                        }
                }
+
                return $dict;
        }
 
@@ -236,25 +236,33 @@ class ParserTest {
         */
        function getMemoryBreakdown() {
                $memStats = array();
+
                foreach ( $GLOBALS as $name => $value ) {
                        $memStats['$' . $name] = strlen( serialize( $value ) );
                }
+
                $classes = get_declared_classes();
+
                foreach ( $classes as $class ) {
                        $rc = new ReflectionClass( $class );
                        $props = $rc->getStaticProperties();
                        $memStats[$class] = strlen( serialize( $props ) );
                        $methods = $rc->getMethods();
+
                        foreach ( $methods as $method ) {
                                $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
                        }
                }
+
                $functions = get_defined_functions();
+
                foreach ( $functions['user'] as $function ) {
                        $rf = new ReflectionFunction( $function );
                        $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
                }
+
                asort( $memStats );
+
                return $memStats;
        }
 
@@ -274,30 +282,37 @@ class ParserTest {
         * @return Boolean: true if passed all tests, false if any tests failed.
         */
        public function runTestsFromFiles( $filenames ) {
+               $GLOBALS['wgContLang'] = Language::factory( 'en' );
                $this->recorder->start();
                $this->setupDatabase();
                $ok = true;
+
                foreach ( $filenames as $filename ) {
                        $tests = new TestFileIterator( $filename, $this );
                        $ok = $this->runTests( $tests ) && $ok;
                }
+
                $this->teardownDatabase();
                $this->recorder->report();
                $this->recorder->end();
+
                return $ok;
        }
 
        function runTests( $tests ) {
                $ok = true;
+
                foreach ( $tests as $i => $t ) {
                        $result =
                                $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
                        $ok = $ok && $result;
                        $this->recorder->record( $t['test'], $result );
                }
+
                if ( $this->showProgress ) {
                        print "\n";
                }
+
                return $ok;
        }
 
@@ -306,16 +321,21 @@ class ParserTest {
         */
        function getParser( $preprocessor = null ) {
                global $wgParserConf;
+
                $class = $wgParserConf['class'];
                $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
+
                foreach ( $this->hooks as $tag => $callback ) {
                        $parser->setHook( $tag, $callback );
                }
+
                foreach ( $this->functionHooks as $tag => $bits ) {
                        list( $callback, $flags ) = $bits;
                        $parser->setFunctionHook( $tag, $callback, $flags );
                }
+
                wfRunHooks( 'ParserTestParser', array( &$parser ) );
+
                return $parser;
        }
 
@@ -342,7 +362,6 @@ class ParserTest {
                $user = new User();
                $options = ParserOptions::newFromUser( $user );
 
-               $m = array();
                if ( isset( $opts['title'] ) ) {
                        $titleText = $opts['title'];
                }
@@ -356,7 +375,6 @@ class ParserTest {
                $parser = $this->getParser( $preprocessor );
                $title = Title::newFromText( $titleText );
 
-               $matches = array();
                if ( isset( $opts['pst'] ) ) {
                        $out = $parser->preSaveTransform( $input, $title, $user, $options );
                } elseif ( isset( $opts['msg'] ) ) {
@@ -378,15 +396,21 @@ class ParserTest {
                        $out = $output->getText();
 
                        if ( isset( $opts['showtitle'] ) ) {
-                               if ( $output->getTitleText() ) $title = $output->getTitleText();
+                               if ( $output->getTitleText() ) {
+                                       $title = $output->getTitleText();
+                               }
+
                                $out = "$title\n$out";
                        }
+
                        if ( isset( $opts['ill'] ) ) {
                                $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
                        } elseif ( isset( $opts['cat'] ) ) {
                                global $wgOut;
+
                                $wgOut->addCategoryLinks( $output->getCategories() );
                                $cats = $wgOut->getCategoryLinks();
+
                                if ( isset( $cats['normal'] ) ) {
                                        $out = $this->tidy( implode( ' ', $cats['normal'] ) );
                                } else {
@@ -407,7 +431,6 @@ class ParserTest {
                }
        }
 
-
        /**
         * Use a regex to find out the value of an option
         * @param $key String: name of option val to retrieve
@@ -416,6 +439,7 @@ class ParserTest {
         */
        private static function getOptionValue( $key, $opts, $default ) {
                $key = strtolower( $key );
+
                if ( isset( $opts[$key] ) ) {
                        return $opts[$key];
                } else {
@@ -483,6 +507,7 @@ class ParserTest {
                if ( substr( $opt, 0, 1 ) == '"' ) {
                        return substr( $opt, 1, -1 );
                }
+
                if ( substr( $opt, 0, 2 ) == '[[' ) {
                        return substr( $opt, 2, -2 );
                }
@@ -495,9 +520,6 @@ class ParserTest {
         */
        private function setupGlobals( $opts = '', $config = '' ) {
                global $wgDBtype;
-               if ( !isset( $this->uploadDir ) ) {
-                       $this->uploadDir = $this->setupUploadDir();
-               }
 
                # Find out values for some special options.
                $lang =
@@ -523,12 +545,11 @@ class ParserTest {
                                'hashLevels' => 2,
                                'transformVia404' => false,
                        ),
-                       'wgEnableUploads' => true,
+                       'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
                        'wgStyleSheetPath' => '/skins',
                        'wgSitename' => 'MediaWiki',
                        'wgServerName' => 'Britney-Spears',
                        'wgLanguageCode' => $lang,
-                       'wgContLanguageCode' => $lang,
                        'wgDBprefix' => $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_',
                        'wgRawHtml' => isset( $opts['rawhtml'] ),
                        'wgLang' => null,
@@ -577,18 +598,27 @@ class ParserTest {
                }
 
                $this->savedGlobals = array();
+
                foreach ( $settings as $var => $val ) {
                        if ( array_key_exists( $var, $GLOBALS ) ) {
                                $this->savedGlobals[$var] = $GLOBALS[$var];
                        }
+
                        $GLOBALS[$var] = $val;
                }
+
                $langObj = Language::factory( $lang );
                $GLOBALS['wgLang'] = $langObj;
                $GLOBALS['wgContLang'] = $langObj;
                $GLOBALS['wgMemc'] = new FakeMemCachedClient;
                $GLOBALS['wgOut'] = new OutputPage;
 
+               global $wgHooks;
+
+               $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
+               $wgHooks['ParserTestParser'][] = 'ParserTestStaticParserHook::setup';
+               $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
+
                MagicWord::clearCache();
 
                global $wgUser;
@@ -601,16 +631,17 @@ class ParserTest {
         */
        private function listTables() {
                global $wgDBtype;
-               $tables = array( 'user', 'page', 'page_restrictions',
+
+               $tables = array( 'user', 'user_properties', 'page', 'page_restrictions',
                        'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
                        'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
                        'site_stats', 'hitcounter',     'ipblocks', 'image', 'oldimage',
-                       'recentchanges', 'watchlist', 'math', 'interwiki',
+                       'recentchanges', 'watchlist', 'math', 'interwiki', 'logging',
                        'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
-                       'archive', 'user_groups', 'page_props', 'category'
+                       'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
                );
 
-               if ( $wgDBtype === 'mysql' )
+               if ( in_array( $wgDBtype, array( 'mysql', 'sqlite' ) ) )
                        array_push( $tables, 'searchindex' );
 
                // Allow extensions to add to the list of tables to duplicate;
@@ -626,21 +657,26 @@ class ParserTest {
         * Currently this will only be done once per run, and any changes to
         * the db will be visible to later tests in the run.
         */
-       function setupDatabase() {
+       public function setupDatabase() {
                global $wgDBprefix, $wgDBtype;
+
                if ( $this->databaseSetupDone ) {
                        return;
                }
+
                if ( $wgDBprefix === 'parsertest_' || ( $wgDBtype == 'oracle' && $wgDBprefix === 'pt_' ) ) {
                        throw new MWException( 'setupDatabase should be called before setupGlobals' );
                }
+
                $this->databaseSetupDone = true;
                $this->oldTablePrefix = $wgDBprefix;
 
+               # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
+               # It seems to have been fixed since (r55079?).
+               # If it fails, $wgCaches[CACHE_DB] = new HashBagOStuff(); should work around it.
+
                # CREATE TEMPORARY TABLE breaks if there is more than one server
-               # FIXME: r40209 makes temporary tables break even with just one server
-               # FIXME: (bug 15892); disabling the feature entirely as a temporary fix
-               if ( true || wfGetLB()->getServerCount() != 1 ) {
+               if ( wfGetLB()->getServerCount() != 1 ) {
                        $this->useTemporaryTables = false;
                }
 
@@ -658,12 +694,21 @@ class ParserTest {
                        $this->changePrefix( $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_' );
                        $newTableName = $db->tableName( $tbl );
 
-                       if ( $db->tableExists( $tbl ) && $wgDBtype != 'postgres' && $wgDBtype != 'oracle' ) {
+                       if ( $wgDBtype == 'mysql' ) {
+                               $db->query( "DROP TABLE IF EXISTS $newTableName" );
+                       } elseif ( in_array( $wgDBtype, array( 'postgres', 'oracle' ) ) ) {
+                               /* DROPs wouldn't work due to Foreign Key Constraints (bug 14990, r58669)
+                                * Use "DROP TABLE IF EXISTS $newTableName CASCADE" for postgres? That
+                                * syntax would also work for mysql.
+                                */
+                       } elseif ( $db->tableExists( $tbl ) ) {
                                $db->query( "DROP TABLE $newTableName" );
                        }
+
                        # Create new table
                        $db->duplicateTableStructure( $oldTableName, $newTableName, $temporary );
                }
+
                if ( $wgDBtype == 'oracle' )
                        $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
 
@@ -674,72 +719,45 @@ class ParserTest {
                $db->insert( 'interwiki', array(
                        array( 'iw_prefix' => 'wikipedia',
                                   'iw_url'    => 'http://en.wikipedia.org/wiki/$1',
+                                  'iw_api'    => '',
+                                  'iw_wikiid' => '',
                                   'iw_local'  => 0 ),
                        array( 'iw_prefix' => 'meatball',
                                   'iw_url'    => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
+                                  'iw_api'    => '',
+                                  'iw_wikiid' => '',
                                   'iw_local'  => 0 ),
                        array( 'iw_prefix' => 'zh',
                                   'iw_url'    => 'http://zh.wikipedia.org/wiki/$1',
+                                  'iw_api'    => '',
+                                  'iw_wikiid' => '',
                                   'iw_local'  => 1 ),
                        array( 'iw_prefix' => 'es',
                                   'iw_url'    => 'http://es.wikipedia.org/wiki/$1',
+                                  'iw_api'    => '',
+                                  'iw_wikiid' => '',
                                   'iw_local'  => 1 ),
                        array( 'iw_prefix' => 'fr',
                                   'iw_url'    => 'http://fr.wikipedia.org/wiki/$1',
+                                  'iw_api'    => '',
+                                  'iw_wikiid' => '',
                                   'iw_local'  => 1 ),
                        array( 'iw_prefix' => 'ru',
                                   'iw_url'    => 'http://ru.wikipedia.org/wiki/$1',
+                                  'iw_api'    => '',
+                                  'iw_wikiid' => '',
                                   'iw_local'  => 1 ),
                        ) );
 
 
                if ( $wgDBtype == 'oracle' ) {
-                       # Insert 0 and 1 user_ids to prevent FK violations
+                       # Insert 0 user to prevent FK violations
 
                        # Anonymous user
                        $db->insert( 'user', array(
                                'user_id'         => 0,
                                'user_name'       => 'Anonymous' ) );
-
-                       # Hack-on-Hack: Insert a test user to be able to insert an image
-                       $db->insert( 'user', array(
-                               'user_id'         => 1,
-                               'user_name'       => 'Tester' ) );
-               }
-
-               # Hack: Insert an image to work with
-               $db->insert( 'image', array(
-                       'img_name'        => 'Foobar.jpg',
-                       'img_size'        => 12345,
-                       'img_description' => 'Some lame file',
-                       'img_user'        => 1,
-                       'img_user_text'   => 'WikiSysop',
-                       'img_timestamp'   => $db->timestamp( '20010115123500' ),
-                       'img_width'       => 1941,
-                       'img_height'      => 220,
-                       'img_bits'        => 24,
-                       'img_media_type'  => MEDIATYPE_BITMAP,
-                       'img_major_mime'  => "image",
-                       'img_minor_mime'  => "jpeg",
-                       'img_metadata'    => serialize( array() ),
-                       ) );
-
-               # This image will be blacklisted in [[MediaWiki:Bad image list]]
-               $db->insert( 'image', array(
-                       'img_name'        => 'Bad.jpg',
-                       'img_size'        => 12345,
-                       'img_description' => 'zomgnotcensored',
-                       'img_user'        => 1,
-                       'img_user_text'   => 'WikiSysop',
-                       'img_timestamp'   => $db->timestamp( '20010115123500' ),
-                       'img_width'       => 320,
-                       'img_height'      => 240,
-                       'img_bits'        => 24,
-                       'img_media_type'  => MEDIATYPE_BITMAP,
-                       'img_major_mime'  => "image",
-                       'img_minor_mime'  => "jpeg",
-                       'img_metadata'    => serialize( array() ),
-                       ) );
+               }
 
                # Update certain things in site_stats
                $db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
@@ -749,7 +767,36 @@ class ParserTest {
 
                # Make a new message cache
                global $wgMessageCache, $wgMemc;
-               $wgMessageCache = new MessageCache( $wgMemc, true, 3600, '' );
+               $wgMessageCache = new MessageCache( $wgMemc, true, 3600 );
+
+               $this->uploadDir = $this->setupUploadDir();
+               $user = User::createNew( 'WikiSysop' );
+               $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
+               $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
+                       'size'        => 12345,
+                       'width'       => 1941,
+                       'height'      => 220,
+                       'bits'        => 24,
+                       'media_type'  => MEDIATYPE_BITMAP,
+                       'mime'        => 'image/jpeg',
+                       'metadata'    => serialize( array() ),
+                       'sha1'        => sha1( '' ),
+                       'fileExists'  => true
+                       ), $db->timestamp( '20010115123500' ), $user );
+
+               # This image will be blacklisted in [[MediaWiki:Bad image list]]
+               $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
+               $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
+                       'size'        => 12345,
+                       'width'       => 320,
+                       'height'      => 240,
+                       'bits'        => 24,
+                       'media_type'  => MEDIATYPE_BITMAP,
+                       'mime'        => 'image/jpeg',
+                       'metadata'    => serialize( array() ),
+                       'sha1'        => sha1( '' ),
+                       'fileExists'  => true
+                       ), $db->timestamp( '20010115123500' ), $user );
        }
 
        /**
@@ -769,28 +816,32 @@ class ParserTest {
                $db->tablePrefix( $prefix );
        }
 
-       private function teardownDatabase() {
+       public function teardownDatabase() {
                global $wgDBtype;
+
                if ( !$this->databaseSetupDone ) {
                        return;
                }
+               $this->teardownUploadDir( $this->uploadDir );
+
                $this->changePrefix( $this->oldTablePrefix );
                $this->databaseSetupDone = false;
+
                if ( $this->useTemporaryTables ) {
                        # Don't need to do anything
                        return;
                }
 
-               /*
                $tables = $this->listTables();
                $db = wfGetDB( DB_MASTER );
+
                foreach ( $tables as $table ) {
                        $sql = $wgDBtype == 'oracle' ? "DROP TABLE pt_$table DROP CONSTRAINTS" : "DROP TABLE `parsertest_$table`";
                        $db->query( $sql );
                }
-               if ($wgDBtype == 'oracle')
-                       $db->query('BEGIN FILL_WIKI_INFO; END;');
-               */
+
+               if ( $wgDBtype == 'oracle' )
+                       $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
        }
 
        /**
@@ -801,8 +852,10 @@ class ParserTest {
         */
        private function setupUploadDir() {
                global $IP;
+
                if ( $this->keepUploads ) {
                        $dir = wfTempDir() . '/mwParser-images';
+
                        if ( is_dir( $dir ) ) {
                                return $dir;
                        }
@@ -810,16 +863,17 @@ class ParserTest {
                        $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
                }
 
-               wfDebug( "Creating upload directory $dir\n" );
+               // wfDebug( "Creating upload directory $dir\n" );
                if ( file_exists( $dir ) ) {
                        wfDebug( "Already exists!\n" );
                        return $dir;
                }
+
                wfMkdirParents( $dir . '/3/3a' );
                copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
-
                wfMkdirParents( $dir . '/0/09' );
                copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
+
                return $dir;
        }
 
@@ -830,13 +884,10 @@ class ParserTest {
        private function teardownGlobals() {
                RepoGroup::destroySingleton();
                LinkCache::singleton()->clear();
+
                foreach ( $this->savedGlobals as $var => $val ) {
                        $GLOBALS[$var] = $val;
                }
-               if ( isset( $this->uploadDir ) ) {
-                       $this->teardownUploadDir( $this->uploadDir );
-                       unset( $this->uploadDir );
-               }
        }
 
        /**
@@ -925,6 +976,7 @@ class ParserTest {
                if ( $this->showProgress ) {
                        print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
                }
+
                return true;
        }
 
@@ -944,10 +996,13 @@ class ParserTest {
                                # test, in case it succeeded. Show it now:
                                $this->showTesting( $desc );
                        }
+
                        print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
+
                        if ( $this->showOutput ) {
                                print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
                        }
+
                        if ( $this->showDiffs ) {
                                print $this->quickDiff( $result, $html );
                                if ( !$this->wellFormed( $html ) ) {
@@ -955,6 +1010,7 @@ class ParserTest {
                                }
                        }
                }
+
                return false;
        }
 
@@ -1007,7 +1063,7 @@ class ParserTest {
                return preg_replace(
                        array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
                        array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
-                              $this->term->color( 31 ) . '$1' . $this->term->reset() ),
+                                  $this->term->color( 31 ) . '$1' . $this->term->reset() ),
                        $text );
        }
 
@@ -1030,13 +1086,18 @@ class ParserTest {
         * @param $line Integer: the input line number, for reporting errors
         */
        public function addArticle( $name, $text, $line ) {
-               $this->setupGlobals();
+               global $wgCapitalLinks;
+               $oldCapitalLinks = $wgCapitalLinks;
+               $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
+
                $title = Title::newFromText( $name );
+
                if ( is_null( $title ) ) {
                        wfDie( "invalid title at line $line\n" );
                }
 
                $aid = $title->getArticleID( GAID_FOR_UPDATE );
+
                if ( $aid != 0 ) {
                        wfDie( "duplicate article '$name' at line $line\n" );
                }
@@ -1044,41 +1105,53 @@ class ParserTest {
                $art = new Article( $title );
                $art->insertNewArticle( $text, '', false, false );
 
-               $this->teardownGlobals();
+               $wgCapitalLinks = $oldCapitalLinks;
        }
 
        /**
         * Steal a callback function from the primary parser, save it for
         * application to our scary parser. If the hook is not installed,
-        * die a painful dead to warn the others.
+        * abort processing of this file.
         *
         * @param $name String
+        * @return Bool true if tag hook is present
         */
        public function requireHook( $name ) {
                global $wgParser;
+
                $wgParser->firstCallInit( ); // make sure hooks are loaded.
+
                if ( isset( $wgParser->mTagHooks[$name] ) ) {
                        $this->hooks[$name] = $wgParser->mTagHooks[$name];
                } else {
-                       wfDie( "This test suite requires the '$name' hook extension.\n" );
+                       echo "   This test suite requires the '$name' hook extension, skipping.\n";
+                       return false;
                }
+
+               return true;
        }
 
        /**
         * Steal a callback function from the primary parser, save it for
         * application to our scary parser. If the hook is not installed,
-        * die a painful dead to warn the others.
+        * abort processing of this file.
         *
         * @param $name String
+        * @return Bool true if function hook is present
         */
        public function requireFunctionHook( $name ) {
                global $wgParser;
+
                $wgParser->firstCallInit( ); // make sure hooks are loaded.
+
                if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
                        $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
                } else {
-                       wfDie( "This test suite requires the '$name' function hook extension.\n" );
+                       echo "   This test suite requires the '$name' function hook extension, skipping.\n";
+                       return false;
                }
+
+               return true;
        }
 
        /*
@@ -1091,9 +1164,11 @@ class ParserTest {
         */
        private function tidy( $text ) {
                global $wgUseTidy;
+
                if ( $wgUseTidy ) {
-                       $text = Parser::tidy( $text );
+                       $text = MWTidy::tidy( $text );
                }
+
                return $text;
        }
 
@@ -1115,9 +1190,12 @@ class ParserTest {
                        $fragment = $this->extractFragment( $html, $position );
                        $this->mXmlError = "$err at byte $position:\n$fragment";
                        xml_parser_free( $parser );
+
                        return false;
                }
+
                xml_parser_free( $parser );
+
                return true;
        }
 
@@ -1142,8 +1220,14 @@ class ParserTest {
                        $this->term->color( 31 ) .
                        '^' .
                        $this->term->color( 0 );
+
                return "$display\n$caret";
        }
+
+       static function getFakeTimestamp( &$parser, &$ts ) {
+               $ts = 123;
+               return true;
+       }
 }
 
 class AnsiTermColorer {
@@ -1158,7 +1242,9 @@ class AnsiTermColorer {
         */
        public function color( $color ) {
                global $wgCommandLineDarkBg;
+
                $light = $wgCommandLineDarkBg ? "1;" : "0;";
+
                return "\x1b[{$light}{$color}m";
        }
 
@@ -1217,13 +1303,16 @@ class TestRecorder {
        function reportPercentage( $success, $total ) {
                $ratio = wfPercent( 100 * $success / $total );
                print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
+
                if ( $success == $total ) {
                        print $this->term->color( 32 ) . "ALL TESTS PASSED!";
                } else {
                        $failed = $total - $success ;
                        print $this->term->color( 31 ) . "$failed tests failed!";
                }
+
                print $this->term->reset() . "\n";
+
                return ( $success == $total );
        }
 }
@@ -1240,6 +1329,7 @@ class DbTestPreviewer extends TestRecorder  {
         */
        function __construct( $parent ) {
                parent::__construct( $parent );
+
                $this->lb = wfGetLBFactory()->newMainLB();
                // This connection will have the wiki's table prefix, not parsertest_
                $this->db = $this->lb->getConnection( DB_MASTER );
@@ -1250,7 +1340,6 @@ class DbTestPreviewer extends TestRecorder  {
         * and all that fun stuff
         */
        function start() {
-               global $wgDBtype;
                parent::start();
 
                if ( ! $this->db->tableExists( 'testrun' )
@@ -1262,6 +1351,7 @@ class DbTestPreviewer extends TestRecorder  {
                        // We'll make comparisons against the previous run later...
                        $this->prevRun = $this->db->selectField( 'testrun', 'MAX(tr_id)' );
                }
+
                $this->results = array();
        }
 
@@ -1289,6 +1379,7 @@ class DbTestPreviewer extends TestRecorder  {
 
                        $res = $this->db->select( 'testitem', array( 'ti_name', 'ti_success' ),
                                array( 'ti_run' => $this->prevRun ), __METHOD__ );
+
                        foreach ( $res as $row ) {
                                if ( !$this->parent->regex
                                        || preg_match( "/{$this->parent->regex}/i", $row->ti_name ) )
@@ -1309,6 +1400,7 @@ class DbTestPreviewer extends TestRecorder  {
                                } else /* if ( $prevResults[$test] == 0 )*/ {
                                        $before = 'f';
                                }
+
                                if ( !isset( $this->results[$test] ) ) {
                                        $after = 'n';
                                } elseif ( $this->results[$test] == 1 ) {
@@ -1316,7 +1408,9 @@ class DbTestPreviewer extends TestRecorder  {
                                } else /*if ( $this->results[$test] == 0 ) */ {
                                        $after = 'f';
                                }
+
                                $code = $before . $after;
+
                                if ( isset( $table[$code] ) ) {
                                        $breakdown[$code][$test] = $this->getTestStatusInfo( $test, $after );
                                }
@@ -1327,6 +1421,7 @@ class DbTestPreviewer extends TestRecorder  {
                                if ( !empty( $breakdown[$code] ) ) {
                                        $count = count( $breakdown[$code] );
                                        printf( "\n%4d %s\n", $count, $label );
+
                                        foreach ( $breakdown[$code] as $differing_test_name => $statusInfo ) {
                                                print "      * $differing_test_name  [$statusInfo]\n";
                                        }
@@ -1335,30 +1430,31 @@ class DbTestPreviewer extends TestRecorder  {
                } else {
                        print "No previous test runs to compare against.\n";
                }
+
                print "\n";
                parent::report();
        }
 
        /**
-        ** Returns a string giving information about when a test last had a status change.
-        ** Could help to track down when regressions were introduced, as distinct from tests
-        ** which have never passed (which are more change requests than regressions).
+        * Returns a string giving information about when a test last had a status change.
+        * Could help to track down when regressions were introduced, as distinct from tests
+        * which have never passed (which are more change requests than regressions).
         */
        private function getTestStatusInfo( $testname, $after ) {
-
                // If we're looking at a test that has just been removed, then say when it first appeared.
                if ( $after == 'n' ) {
                        $changedRun = $this->db->selectField ( 'testitem',
-                                                                                                  'MIN(ti_run)',
-                                                                                                  array( 'ti_name' => $testname ),
-                                                                                                  __METHOD__ );
+                               'MIN(ti_run)',
+                               array( 'ti_name' => $testname ),
+                               __METHOD__ );
                        $appear = $this->db->selectRow ( 'testrun',
-                                                                                        array( 'tr_date', 'tr_mw_version' ),
-                                                                                        array( 'tr_id' => $changedRun ),
-                                                                                        __METHOD__ );
+                               array( 'tr_date', 'tr_mw_version' ),
+                               array( 'tr_id' => $changedRun ),
+                               __METHOD__ );
+
                        return "First recorded appearance: "
-                              . date( "d-M-Y H:i:s",  strtotime ( $appear->tr_date ) )
-                              .  ", " . $appear->tr_mw_version;
+                                  . date( "d-M-Y H:i:s",  strtotime ( $appear->tr_date ) )
+                                  .  ", " . $appear->tr_mw_version;
                }
 
                // Otherwise, this test has previous recorded results.
@@ -1366,6 +1462,7 @@ class DbTestPreviewer extends TestRecorder  {
                $conds = array(
                        'ti_name'    => $testname,
                        'ti_success' => ( $after == 'f' ? "1" : "0" ) );
+
                if ( $this->curRun ) {
                        $conds[] = "ti_run != " . $this->db->addQuotes ( $this->curRun );
                }
@@ -1385,21 +1482,22 @@ class DbTestPreviewer extends TestRecorder  {
                // (i.e. it used to work, but now doesn't; or used to fail, but is now fixed.)
                // In this situation, give as much info as we can as to when it changed status.
                $pre  = $this->db->selectRow ( 'testrun',
-                                                                               array( 'tr_date', 'tr_mw_version' ),
-                                                                               array( 'tr_id' => $changedRun ),
-                                                                               __METHOD__ );
+                       array( 'tr_date', 'tr_mw_version' ),
+                       array( 'tr_id' => $changedRun ),
+                       __METHOD__ );
                $post = $this->db->selectRow ( 'testrun',
-                                                                               array( 'tr_date', 'tr_mw_version' ),
-                                                                               array( "tr_id > " . $this->db->addQuotes ( $changedRun ) ),
-                                                                               __METHOD__,
-                                                                               array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
-                                                                        );
+                       array( 'tr_date', 'tr_mw_version' ),
+                       array( "tr_id > " . $this->db->addQuotes ( $changedRun ) ),
+                       __METHOD__,
+                       array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
+               );
 
                if ( $post ) {
                        $postDate = date( "d-M-Y H:i:s",  strtotime ( $post->tr_date  ) ) . ", {$post->tr_mw_version}";
                } else {
                        $postDate = 'now';
                }
+
                return ( $after == "f" ? "Introduced" : "Fixed" ) . " between "
                                . date( "d-M-Y H:i:s",  strtotime ( $pre->tr_date ) ) .  ", " . $pre->tr_mw_version
                                . " and $postDate";
@@ -1418,24 +1516,28 @@ class DbTestPreviewer extends TestRecorder  {
 }
 
 class DbTestRecorder extends DbTestPreviewer  {
+       var $version;
+
        /**
         * Set up result recording; insert a record for the run with the date
         * and all that fun stuff
         */
        function start() {
-               global $wgDBtype, $options;
+               global $wgDBtype;
                $this->db->begin();
 
                if ( ! $this->db->tableExists( 'testrun' )
                        or ! $this->db->tableExists( 'testitem' ) )
                {
                        print "WARNING> `testrun` table not found in database. Trying to create table.\n";
-                       if ( $wgDBtype === 'postgres' )
+                       if ( $wgDBtype === 'postgres' ) {
                                $this->db->sourceFile( dirname( __FILE__ ) . '/testRunner.postgres.sql' );
-                       elseif ( $wgDBtype === 'oracle' )
+                       } elseif ( $wgDBtype === 'oracle' ) {
                                $this->db->sourceFile( dirname( __FILE__ ) . '/testRunner.ora.sql' );
-                       else
+                       } else {
                                $this->db->sourceFile( dirname( __FILE__ ) . '/testRunner.sql' );
+                       }
+
                        echo "OK, resuming.\n";
                }
 
@@ -1444,17 +1546,17 @@ class DbTestRecorder extends DbTestPreviewer  {
                $this->db->insert( 'testrun',
                        array(
                                'tr_date'        => $this->db->timestamp(),
-                               'tr_mw_version'  => isset( $options['setversion'] ) ?
-                                       $options['setversion'] : SpecialVersion::getVersion(),
+                               'tr_mw_version'  => $this->version,
                                'tr_php_version' => phpversion(),
                                'tr_db_version'  => $this->db->getServerVersion(),
                                'tr_uname'       => php_uname()
                        ),
                        __METHOD__ );
-                       if ( $wgDBtype === 'postgres' )
+                       if ( $wgDBtype === 'postgres' ) {
                                $this->curRun = $this->db->currentSequenceValue( 'testrun_id_seq' );
-                       else
+                       } else {
                                $this->curRun = $this->db->insertId();
+                       }
        }
 
        /**
@@ -1465,6 +1567,7 @@ class DbTestRecorder extends DbTestPreviewer  {
         */
        function record( $test, $result ) {
                parent::record( $test, $result );
+
                $this->db->insert( 'testitem',
                        array(
                                'ti_run'     => $this->curRun,
@@ -1478,6 +1581,7 @@ class DbTestRecorder extends DbTestPreviewer  {
 class RemoteTestRecorder extends TestRecorder {
        function start() {
                parent::start();
+
                $this->results = array();
                $this->ping( 'running' );
        }
@@ -1505,7 +1609,7 @@ class RemoteTestRecorder extends TestRecorder {
 
                $remote = $wgParserTestRemote;
                $revId = SpecialVersion::getSvnRevision( $IP );
-               $jsonResults = json_encode( $results );
+               $jsonResults = FormatJson::encode( $results );
 
                if ( !$remote ) {
                        print "Can't do remote upload without configuring \$wgParserTestRemote!\n";
@@ -1519,6 +1623,7 @@ class RemoteTestRecorder extends TestRecorder {
                        $revId,
                        $status,
                );
+
                if ( $status == "complete" ) {
                        $message[] = $jsonResults;
                }
@@ -1533,21 +1638,26 @@ class RemoteTestRecorder extends TestRecorder {
                        'status' => $status,
                        'hmac'   => $hmac,
                );
+
                if ( $status == "complete" ) {
                        $postData['results'] = $jsonResults;
                }
+
                $response = $this->post( $remote['api-url'], $postData );
 
                if ( $response === false ) {
                        print "CodeReview info upload failed to reach server.\n";
                        exit( 1 );
                }
+
                $responseData = FormatJson::decode( $response, true );
+
                if ( !is_array( $responseData ) ) {
                        print "CodeReview API response not recognized...\n";
                        wfDebug( "Unrecognized CodeReview API response: $response\n" );
                        exit( 1 );
                }
+
                if ( isset( $responseData['error'] ) ) {
                        $code = $responseData['error']['code'];
                        $info = $responseData['error']['info'];
@@ -1562,11 +1672,11 @@ class RemoteTestRecorder extends TestRecorder {
 }
 
 class TestFileIterator implements Iterator {
-    private $file;
-    private $fh;
-    private $parser;
-    private $index = 0;
-    private $test;
+       private $file;
+       private $fh;
+       private $parser;
+       private $index = 0;
+       private $test;
        private $lineNum;
        private $eof;
 
@@ -1574,14 +1684,18 @@ class TestFileIterator implements Iterator {
                global $IP;
 
                $this->file = $file;
-       $this->fh = fopen( $this->file, "rt" );
-        if ( !$this->fh ) {
+               $this->fh = fopen( $this->file, "rt" );
+
+               if ( !$this->fh ) {
                        wfDie( "Couldn't open file '$file'\n" );
                }
 
                $this->parser = $parser;
 
-               if ( $this->parser ) $this->parser->showRunFile( wfRelativePath( $this->file, $IP ) );
+               if ( $this->parser ) {
+                       $this->parser->showRunFile( wfRelativePath( $this->file, $IP ) );
+               }
+
                $this->lineNum = $this->index = 0;
        }
 
@@ -1591,36 +1705,37 @@ class TestFileIterator implements Iterator {
 
        function rewind() {
                if ( fseek( $this->fh, 0 ) ) {
-                       wfDie( "Couldn't fseek to the start of '$filename'\n" );
+                       wfDie( "Couldn't fseek to the start of '$this->file'\n" );
                }
+
                $this->index = -1;
                $this->lineNum = 0;
                $this->eof = false;
                $this->next();
 
                return true;
-    }
+       }
 
-    function current() {
+       function current() {
                return $this->test;
-    }
+       }
 
-    function key() {
+       function key() {
                return $this->index;
-    }
+       }
 
-    function next() {
-        if ( $this->readNextTest() ) {
+       function next() {
+               if ( $this->readNextTest() ) {
                        $this->index++;
                        return true;
                } else {
                        $this->eof = true;
                }
-    }
+       }
 
-    function valid() {
+       function valid() {
                return $this->eof != true;
-    }
+       }
 
        function readNextTest() {
                $data = array();
@@ -1629,64 +1744,89 @@ class TestFileIterator implements Iterator {
                while ( false !== ( $line = fgets( $this->fh ) ) ) {
                        $this->lineNum++;
                        $matches = array();
+
                        if ( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
                                $section = strtolower( $matches[1] );
+
                                if ( $section == 'endarticle' ) {
                                        if ( !isset( $data['text'] ) ) {
-                                               wfDie( "'endarticle' without 'text' at line {$this->lineNum} of $filename\n" );
+                                               wfDie( "'endarticle' without 'text' at line {$this->lineNum} of $this->file\n" );
                                        }
+
                                        if ( !isset( $data['article'] ) ) {
-                                               wfDie( "'endarticle' without 'article' at line {$this->lineNum} of $filename\n" );
+                                               wfDie( "'endarticle' without 'article' at line {$this->lineNum} of $this->file\n" );
                                        }
+
                                        if ( $this->parser ) {
                                                $this->parser->addArticle( $this->parser->chomp( $data['article'] ), $this->parser->chomp( $data['text'] ),
                                                        $this->lineNum );
                                        }
+
                                        $data = array();
                                        $section = null;
+
                                        continue;
                                }
+
                                if ( $section == 'endhooks' ) {
                                        if ( !isset( $data['hooks'] ) ) {
-                                               wfDie( "'endhooks' without 'hooks' at line {$this->lineNum} of $filename\n" );
+                                               wfDie( "'endhooks' without 'hooks' at line {$this->lineNum} of $this->file\n" );
                                        }
+
                                        foreach ( explode( "\n", $data['hooks'] ) as $line ) {
                                                $line = trim( $line );
+
                                                if ( $line ) {
-                                                       if ( $this->parser ) $this->parser->requireHook( $line );
+                                                       if ( $this->parser && !$this->parser->requireHook( $line ) ) {
+                                                               return false;
+                                                       }
                                                }
                                        }
+
                                        $data = array();
                                        $section = null;
+
                                        continue;
                                }
+
                                if ( $section == 'endfunctionhooks' ) {
                                        if ( !isset( $data['functionhooks'] ) ) {
-                                               wfDie( "'endfunctionhooks' without 'functionhooks' at line {$this->lineNum} of $filename\n" );
+                                               wfDie( "'endfunctionhooks' without 'functionhooks' at line {$this->lineNum} of $this->file\n" );
                                        }
+
                                        foreach ( explode( "\n", $data['functionhooks'] ) as $line ) {
                                                $line = trim( $line );
+
                                                if ( $line ) {
-                                                       if ( $this->parser ) $this->parser->requireFunctionHook( $line );
+                                                       if ( $this->parser && !$this->parser->requireFunctionHook( $line ) ) {
+                                                               return false;
+                                                       }
                                                }
                                        }
+
                                        $data = array();
                                        $section = null;
+
                                        continue;
                                }
+
                                if ( $section == 'end' ) {
                                        if ( !isset( $data['test'] ) ) {
-                                               wfDie( "'end' without 'test' at line {$this->lineNum} of $filename\n" );
+                                               wfDie( "'end' without 'test' at line {$this->lineNum} of $this->file\n" );
                                        }
+
                                        if ( !isset( $data['input'] ) ) {
-                                               wfDie( "'end' without 'input' at line {$this->lineNum} of $filename\n" );
+                                               wfDie( "'end' without 'input' at line {$this->lineNum} of $this->file\n" );
                                        }
+
                                        if ( !isset( $data['result'] ) ) {
-                                               wfDie( "'end' without 'result' at line {$this->lineNum} of $filename\n" );
+                                               wfDie( "'end' without 'result' at line {$this->lineNum} of $this->file\n" );
                                        }
+
                                        if ( !isset( $data['options'] ) ) {
                                                $data['options'] = '';
                                        }
+
                                        if ( !isset( $data['config'] ) )
                                                $data['config'] = '';
 
@@ -1696,13 +1836,18 @@ class TestFileIterator implements Iterator {
                                                # disabled test
                                                $data = array();
                                                $section = null;
+
                                                continue;
                                        }
+
+                                       global $wgUseTeX;
+
                                        if ( $this->parser &&
-                                                preg_match( '/\\bmath\\b/i', $data['options'] ) && !$this->parser->savedGlobals['wgUseTeX'] ) {
+                                                preg_match( '/\\bmath\\b/i', $data['options'] ) && !$wgUseTeX ) {
                                                # don't run math tests if $wgUseTeX is set to false in LocalSettings
                                                $data = array();
                                                $section = null;
+
                                                continue;
                                        }
 
@@ -1716,18 +1861,24 @@ class TestFileIterator implements Iterator {
                                        } else {
                                                $this->test['test'] = $data['test'];
                                        }
+
                                        return true;
                                }
+
                                if ( isset ( $data[$section] ) ) {
-                                       wfDie( "duplicate section '$section' at line {$this->lineNum} of $filename\n" );
+                                       wfDie( "duplicate section '$section' at line {$this->lineNum} of $this->file\n" );
                                }
+
                                $data[$section] = '';
+
                                continue;
                        }
+
                        if ( $section ) {
                                $data[$section] .= $line;
                        }
                }
+
                return false;
        }
 }