Example #1
0
    def test_parse_ini_file_no_default_section_header(self, mock_config_parser_type):
        s1 = {
            'key1': 'value11',
            'key2': 'value22',
        }
        s2 = {
            'key1': 'value123',
            'key2': 'value234',
        }

        mock_config_parser = mock_config_parser_type()
        mock_config_parser.read.return_value = True
        mock_config_parser.sections.return_value = ['s1', 's2']
        mock_config_parser.items.side_effect = iter([
            configparser.NoSectionError(mock.Mock()),
            s1.items(),
            s2.items(),
        ])

        expected = {
            'DEFAULT': {},
            's1': s1,
            's2': s2,
        }
        result = utils.parse_ini_file('my_path')
        self.assertDictEqual(result, expected)
    def remove_comment(self, section, option=None):
        """
        Remove the comment from a section or option.

        @type section: str
        @param section: The section to remove from.

        @type option: str or None
        @param option: The option to remove from or None to remove a section's
        comment.

        @rtype: bool
        @return: True if a comment was removed and False if no comment was
        removed.

        """
        if not section:
            section = configparser.DEFAULTSECT
        elif not self.has_section(section) and \
                section != configparser.DEFAULTSECT:
            raise configparser.NoSectionError(section)

        if option:
            option = self.optionxform(option)
            if not self.has_option(section, option):
                raise configparser.NoOptionError(option, section)
        else:
            # setting section comment
            option = '__name__'

        del self._comments[section][option]
Example #3
0
    def parse_config_files(self):
        """
        Parse the possible config files and set appropriate values
        default values
        """
        parser = configparser.SafeConfigParser()
        # Fill in the built in values
        self.config = dict(self.__class__.defaults)
        # Update with the values from the defaults section. This is needed
        # in case the config file doesn't have a [<command>] section at all
        config_files = self.get_config_files()
        try:
            repo = GitRepository(".")
        except GitRepositoryError:
            repo = None
        # Read all config files
        for filename in config_files:
            self._read_config_file(parser, repo, filename)
        self.config.update(dict(parser.defaults()))

        # Make sure we read any legacy sections prior to the real subcommands
        # section i.e. read [gbp-pull] prior to [pull]
        if (self.command.startswith('gbp-')
                or self.command.startswith('git-')):
            cmd = self.command[4:]
            oldcmd = self.command
            if parser.has_section(oldcmd):
                self.config.update(dict(parser.items(oldcmd, raw=True)))
                gbp.log.warn("Old style config section [%s] found "
                             "please rename to [%s]" % (oldcmd, cmd))
        else:
            cmd = self.command
            for prefix in ['gbp', 'git']:
                oldcmd = '%s-%s' % (prefix, self.command)
                if parser.has_section(oldcmd):
                    self.config.update(dict(parser.items(oldcmd, raw=True)))
                    gbp.log.warn("Old style config section [%s] found "
                                 "please rename to [%s]" % (oldcmd, cmd))

        # Update with command specific settings
        if parser.has_section(cmd):
            # Don't use items() until we got rid of the compat sections
            # since this pulls in the defaults again
            self.config.update(dict(parser._sections[cmd].items()))

        for section in self.sections:
            if parser.has_section(section):
                self.config.update(dict(parser._sections[section].items()))
            else:
                raise configparser.NoSectionError(
                    "Mandatory section [%s] does not exist." % section)

        # filter can be either a list or a string, always build a list:
        if self.config['filter']:
            if self.config['filter'].startswith('['):
                self.config['filter'] = eval(self.config['filter'])
            else:
                self.config['filter'] = [self.config['filter']]
        else:
            self.config['filter'] = []
    def has_comment(self, section, option=None):
        """
        Return if the given section heading or option within a section has an
        associated comment.

        @type section: str
        @type option: str or None
        @rtype: bool

        @raise NoSectionError: The provided section does not exist

        """
        if not section:
            section = configparser.DEFAULTSECT

        if not self.has_section(section) and \
                section != configparser.DEFAULTSECT:
            raise configparser.NoSectionError(section)

        if option:
            option = self.optionxform(option)
            if not self.has_option(section, option):
                raise configparser.NoOptionError(option, section)
        else:
            # looking for section comment
            option = '__name__'

        return bool(
            self._comments.get(section, False)
            and self._comments[section].get(option, False))
    def set_comment(self, comment, section, option=None):
        """
        Set the comment for a section or option

        @type comment: str or None
        @type section: str
        @type option: str or None

        """
        if not section:
            section = configparser.DEFAULTSECT

        if not self.has_section(section) and \
                section != configparser.DEFAULTSECT:
            raise configparser.NoSectionError(section)

        if section not in self._comments:
            self._comments[section] = self._dict()

        if option:
            option = self.optionxform(option)
            if not self.has_option(section, option):
                raise configparser.NoOptionError(option, section)
        else:
            # setting section comment
            option = '__name__'

        self._comments[section][option] = comment
Example #6
0
 def get_value(self, section, option):
     for cfg in self._configs:
         try:
             return cfg.get_value(section, option)
         except (configparser.NoSectionError, configparser.NoOptionError):
             pass
     if not self.has_section(section):
         raise configparser.NoSectionError(section)
     raise configparser.NoOptionError(option, section)
Example #7
0
    def test_get_analytics_id_when_not_exists(self, uuid):
        aid = 'id'
        uuid.uuid4.return_value = aid

        config_mock = Mock()
        config_mock.get.side_effect = configparser.NoSectionError('msg')

        manager = AccountManager(config_mock)
        self.assertEquals(aid, manager.analytics_id)

        config_mock.set.assert_called_once_with('User', 'analytics_id', aid)
        config_mock.write.assert_called_once()
Example #8
0
    def test_exception_raised_select_template_no_config(self, mock_exit):
        arguments = PropertyMock(return_value={'--select': True})
        type(self.interface).arguments = arguments
        self.config.items.side_effect = ConfigParser.NoSectionError('template')

        s = Settings(self.interface, self.config)

        with self.assertRaises(FacioException):
            with self.assertRaises(ConfigParser.NoSectionError):
                s.get_template_path()
        self.mocked_facio_exceptions_puts.assert_any_call(
            'Error: Missing [template] section in Facio configuration file.')
        self.assertTrue(mock_exit.called)
Example #9
0
    def get_location(self, section, option):
        """Get location information for an option value in a given section.

        Returns a tuple (filename, line_number) if location information
        exists, and None otherwise.
        """

        if not self.has_section(section):
            raise configparser.NoSectionError(section)
        elif not self.has_option(section, option):
            raise configparser.NoOptionError(option, section)
        option = self.optionxform(option)
        loc = self._option_lines[section].get(option)
        if loc is None and option in self._defaults:
            return self._option_lines[configparser.DEFAULTSECT].get(option)
        return loc
Example #10
0
    def set_location(self, section, option, location):
        """Explicitly set location information for an option value in a given
        section. `location' must be a tuple of (filename, line_number).
        """

        if not self.has_section(section):
            raise configparser.NoSectionError(section)
        elif not self.has_option(section, option):
            raise configparser.NoOptionError(option, section)

        if location is not None:
            try:
                filename, lineno = location
            except ValueError:
                err = ValueError("location must be (filename, lineno) or None")
                six.raise_from(err, None)
        option = self.optionxform(option)
        self._option_lines[section][option] = location
    def get_comment(self, section, option=None):
        """
        Get the comment for a section[.option]

        @type section: str
        @param section: Section heading to check for a comment, or the section
        heading that the target option is located under.

        @type option: str or None
        @param option: If checking for an option's comment, this is the option
        under the given section to check. If checking for a section's comment,
        this should be None.

        @rtype: str or None
        @return: The section or option comment if there is one, or None if there
        is no comment for the specified section or option.

        """
        if not section:
            section = configparser.DEFAULTSECT

        if not self.has_section(section) and \
                section != configparser.DEFAULTSECT:
            raise configparser.NoSectionError(section)

        if option:
            option = self.optionxform(option)
            if not self.has_option(section, option):
                raise configparser.NoOptionError(option, section)

        else:
            # looking for section comment
            option = '__name__'

        # Combined statement to handle both section and option requests.
        return (self._comments.get(section, None)
                and self._comments[section].get(option, None))
Example #12
0
    def test_empty_render_ignore_no_section(self):
        self.config.get.side_effect = ConfigParser.NoSectionError('files')

        s = Settings(self.interface, self.config)

        self.assertEqual(s.render_ignore_globs(), [])