当前位置: 首页>>代码示例>>Python>>正文


Python ConfParser.parse方法代码示例

本文整理汇总了Python中coalib.parsing.ConfParser.ConfParser.parse方法的典型用法代码示例。如果您正苦于以下问题:Python ConfParser.parse方法的具体用法?Python ConfParser.parse怎么用?Python ConfParser.parse使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在coalib.parsing.ConfParser.ConfParser的用法示例。


在下文中一共展示了ConfParser.parse方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_remove_empty_iter_elements

# 需要导入模块: from coalib.parsing.ConfParser import ConfParser [as 别名]
# 或者: from coalib.parsing.ConfParser.ConfParser import parse [as 别名]
    def test_remove_empty_iter_elements(self):
        # Test with empty-elem stripping.
        uut = ConfParser(remove_empty_iter_elements=True)
        uut.parse(self.file)
        self.assertEqual(list(uut.get_section("EMPTY_ELEM_STRIP")["A"]),
                         ["a", "b", "c"])
        self.assertEqual(list(uut.get_section("EMPTY_ELEM_STRIP")["B"]),
                         ["a", "d"])
        self.assertEqual(list(uut.get_section("EMPTY_ELEM_STRIP")["C"]),
                         [])

        # Test without stripping.
        uut = ConfParser(remove_empty_iter_elements=False)
        uut.parse(self.file)
        self.assertEqual(list(uut.get_section("EMPTY_ELEM_STRIP")["A"]),
                         ["a", "b", "c"])
        self.assertEqual(list(uut.get_section("EMPTY_ELEM_STRIP")["B"]),
                         ["a", "", "", "d"])
        self.assertEqual(list(uut.get_section("EMPTY_ELEM_STRIP")["C"]),
                         ["", "", "", ""])
开发者ID:nishant-mor,项目名称:coala,代码行数:22,代码来源:ConfParserTest.py

示例2: test_remove_empty_iter_elements

# 需要导入模块: from coalib.parsing.ConfParser import ConfParser [as 别名]
# 或者: from coalib.parsing.ConfParser.ConfParser import parse [as 别名]
    def test_remove_empty_iter_elements(self):
        # Test with empty-elem stripping.
        uut = ConfParser(remove_empty_iter_elements=True)
        uut.parse(self.file)
        self.assertEqual(list(uut.get_section('EMPTY_ELEM_STRIP')['A']),
                         ['a', 'b', 'c'])
        self.assertEqual(list(uut.get_section('EMPTY_ELEM_STRIP')['B']),
                         ['a', 'd'])
        self.assertEqual(list(uut.get_section('EMPTY_ELEM_STRIP')['C']),
                         [])

        # Test without stripping.
        uut = ConfParser(remove_empty_iter_elements=False)
        uut.parse(self.file)
        self.assertEqual(list(uut.get_section('EMPTY_ELEM_STRIP')['A']),
                         ['a', 'b', 'c'])
        self.assertEqual(list(uut.get_section('EMPTY_ELEM_STRIP')['B']),
                         ['a', '', '', 'd'])
        self.assertEqual(list(uut.get_section('EMPTY_ELEM_STRIP')['C']),
                         ['', '', '', ''])
开发者ID:RohanVB,项目名称:coala,代码行数:22,代码来源:ConfParserTest.py

示例3: ConfWriterTest

# 需要导入模块: from coalib.parsing.ConfParser import ConfParser [as 别名]
# 或者: from coalib.parsing.ConfParser.ConfParser import parse [as 别名]
class ConfWriterTest(unittest.TestCase):
    example_file = ("to be ignored \n"
                    "    save=true\n"
                    "    a_default, another = val \n"
                    "    TEST = tobeignored  # thats a comment \n"
                    "    test = push \n"
                    "    t = \n"
                    "    [MakeFiles] \n"
                    "     j  , ANother = a \n"
                    "                   multiline \n"
                    "                   value \n"
                    "    ; just a omment \n"
                    "    ; just a omment \n")

    def setUp(self):
        self.file = os.path.join(tempfile.gettempdir(), "ConfParserTestFile")
        with open(self.file, "w", encoding='utf-8') as filehandler:
            filehandler.write(self.example_file)

        self.conf_parser = ConfParser()
        self.write_file_name = os.path.join(tempfile.gettempdir(),
                                            "ConfWriterTestFile")
        self.uut = ConfWriter(self.write_file_name)

    def tearDown(self):
        self.uut.close()
        os.remove(self.file)
        os.remove(self.write_file_name)

    def test_exceptions(self):
        self.assertRaises(TypeError, self.uut.write_section, 5)

    def test_write(self):
        result_file = ["[Default]\n",
                       "save = true\n",
                       "a_default, another = val\n",
                       "# thats a comment\n",
                       "test = push\n",
                       "t = \n",
                       "\n",
                       "[MakeFiles]\n",
                       "j, ANother = a\n",
                       "multiline\n",
                       "value\n",
                       "; just a omment\n",
                       "; just a omment\n"]
        self.uut.write_sections(self.conf_parser.parse(self.file))
        self.uut.close()

        with open(self.write_file_name, "r") as f:
            lines = f.readlines()

        self.assertEqual(result_file, lines)
开发者ID:gaurav-kispotta,项目名称:coala,代码行数:55,代码来源:ConfWriterTest.py

示例4: load

# 需要导入模块: from coalib.parsing.ConfParser import ConfParser [as 别名]
# 或者: from coalib.parsing.ConfParser.ConfParser import parse [as 别名]
    def load(cls, language: str, docstyle: str, coalang_dir=None):
        """
        Loads a ``DocstyleDefinition`` from the coala docstyle definition files.

        This function considers all settings inside the according coalang-files
        as markers.

        :param language:           The case insensitive programming language of
                                   the documentation comment as a string.
        :param docstyle:           The case insensitive documentation
                                   style/tool used to document code, e.g.
                                   ``"default"`` or ``"doxygen"``.
        :param coalang_dir:        Path to directory with coalang docstyle
                                   definition files. This replaces the default
                                   path if given.
        :raises FileNotFoundError: Raised when the given docstyle was not
                                   found.
        :raises KeyError:          Raised when the given language is not
                                   defined for given docstyle.
        :return:                   The ``DocstyleDefinition`` for given language
                                   and docstyle.
        """

        docstyle = docstyle.lower()

        language_config_parser = ConfParser(remove_empty_iter_elements=False)

        coalang_file = os.path.join(
            coalang_dir or os.path.dirname(__file__), docstyle + ".coalang")

        try:
            docstyle_settings = language_config_parser.parse(coalang_file)
        except FileNotFoundError:
            raise FileNotFoundError("Docstyle definition " + repr(docstyle) +
                                    " not found.")

        language = language.lower()

        try:
            docstyle_settings = docstyle_settings[language]
        except KeyError:
            raise KeyError("Language {!r} is not defined for docstyle {!r}."
                           .format(language, docstyle))

        marker_sets = (tuple(value)
                       for key, value in
                       filter(lambda kv: not kv[0].startswith("comment"),
                              docstyle_settings.contents.items()))

        return cls(language, docstyle, marker_sets)
开发者ID:AndreaCrotti,项目名称:coala,代码行数:52,代码来源:DocstyleDefinition.py

示例5: get_available_definitions

# 需要导入模块: from coalib.parsing.ConfParser import ConfParser [as 别名]
# 或者: from coalib.parsing.ConfParser.ConfParser import parse [as 别名]
    def get_available_definitions():
        """
        Returns a sequence of pairs with ``(docstyle, language)`` which are
        available when using ``load()``.

        :return: A sequence of pairs with ``(docstyle, language)``.
        """
        language_config_parser = ConfParser(remove_empty_iter_elements=False)
        pattern = os.path.join(os.path.dirname(__file__), '*.coalang')

        for coalang_file in iglob(pattern):
            docstyle = os.path.splitext(os.path.basename(coalang_file))[0]
            # Ignore files that are not lowercase, as coalang files have to be.
            if docstyle.lower() == docstyle:
                for language in language_config_parser.parse(coalang_file):
                    yield docstyle, language.lower()
开发者ID:RohanVB,项目名称:coala,代码行数:18,代码来源:DocstyleDefinition.py

示例6: ConfParserTest

# 需要导入模块: from coalib.parsing.ConfParser import ConfParser [as 别名]
# 或者: from coalib.parsing.ConfParser.ConfParser import parse [as 别名]
class ConfParserTest(unittest.TestCase):
    example_file = """to be ignored
    a_default, another = val
    TEST = tobeignored  # do you know that thats a comment
    test = push
    t =
    escaped_\\=equal = escaped_\\#hash
    escaped_\\\\backslash = escaped_\\ space
    escaped_\\,comma = escaped_\\.dot
    [MakeFiles]
     j  , another = a
                   multiline
                   value
    # just a omment
    # just a omment
    nokey. = value
    default.test = content
    makefiles.lastone = val

    [EMPTY_ELEM_STRIP]
    A = a, b, c
    B = a, ,, d
    C = ,,,
    """

    def setUp(self):
        self.tempdir = tempfile.gettempdir()
        self.file = os.path.join(self.tempdir, '.coafile')
        self.nonexistentfile = os.path.join(self.tempdir, 'e81k7bd98t')
        with open(self.file, 'w') as file:
            file.write(self.example_file)

        self.uut = ConfParser()
        try:
            os.remove(self.nonexistentfile)
        except FileNotFoundError:
            pass

        self.sections = self.uut.parse(self.file)

    def tearDown(self):
        os.remove(self.file)

    def test_parse_nonexisting_file(self):
        self.assertRaises(FileNotFoundError,
                          self.uut.parse,
                          self.nonexistentfile)
        self.assertNotEqual(self.uut.parse(self.file, True), self.sections)

    def test_parse_nonexisting_section(self):
        self.assertRaises(IndexError,
                          self.uut.get_section,
                          'inexistent section')

    def test_parse_default_section(self):
        default_should = OrderedDict([
            ('a_default', 'val'),
            ('another', 'val'),
            ('comment0', '# do you know that thats a comment'),
            ('test', 'content'),
            ('t', ''),
            ('escaped_=equal', 'escaped_#hash'),
            ('escaped_\\backslash', 'escaped_ space'),
            ('escaped_,comma', 'escaped_.dot')])

        key, val = self.sections.popitem(last=False)
        self.assertTrue(isinstance(val, Section))
        self.assertEqual(key, 'default')

        is_dict = OrderedDict()
        for k in val:
            is_dict[k] = str(val[k])
        self.assertEqual(is_dict, default_should)

    def test_parse_makefiles_section(self):
        makefiles_should = OrderedDict([
            ('j', 'a\nmultiline\nvalue'),
            ('another', 'a\nmultiline\nvalue'),
            ('comment1', '# just a omment'),
            ('comment2', '# just a omment'),
            ('lastone', 'val'),
            ('comment3', ''),
            ('a_default', 'val'),
            ('comment0', '# do you know that thats a comment'),
            ('test', 'content'),
            ('t', ''),
            ('escaped_=equal', 'escaped_#hash'),
            ('escaped_\\backslash', 'escaped_ space'),
            ('escaped_,comma', 'escaped_.dot')])

        # Pop off the default section.
        self.sections.popitem(last=False)

        key, val = self.sections.popitem(last=False)
        self.assertTrue(isinstance(val, Section))
        self.assertEqual(key, 'makefiles')

        is_dict = OrderedDict()
        for k in val:
            is_dict[k] = str(val[k])
#.........这里部分代码省略.........
开发者ID:RohanVB,项目名称:coala,代码行数:103,代码来源:ConfParserTest.py

示例7: load

# 需要导入模块: from coalib.parsing.ConfParser import ConfParser [as 别名]
# 或者: from coalib.parsing.ConfParser.ConfParser import parse [as 别名]
    def load(cls, language: str, docstyle: str, coalang_dir=None):
        """
        Loads a ``DocstyleDefinition`` from the coala docstyle definition files.

        This function considers all settings inside the according coalang-files
        as markers, except ``param_start``, ``param_end`` and ``return_sep``
        which are considered as special metadata markers.

        .. note::

            When placing new coala docstyle definition files, these must
            consist of only lowercase letters and end with ``.coalang``!

        :param language:           The case insensitive programming language of
                                   the documentation comment as a string.
        :param docstyle:           The case insensitive documentation
                                   style/tool used to document code, e.g.
                                   ``"default"`` or ``"doxygen"``.
        :param coalang_dir:        Path to directory with coalang docstyle
                                   definition files. This replaces the default
                                   path if given.
        :raises FileNotFoundError: Raised when the given docstyle was not
                                   found.
        :raises KeyError:          Raised when the given language is not
                                   defined for given docstyle.
        :return:                   The ``DocstyleDefinition`` for given language
                                   and docstyle.
        """

        docstyle = docstyle.lower()

        language_config_parser = ConfParser(remove_empty_iter_elements=False)

        coalang_file = os.path.join(
            coalang_dir or os.path.dirname(__file__), docstyle + '.coalang')

        try:
            docstyle_settings = language_config_parser.parse(coalang_file)
        except FileNotFoundError:
            raise FileNotFoundError('Docstyle definition ' + repr(docstyle) +
                                    ' not found.')

        language = language.lower()

        try:
            docstyle_settings = docstyle_settings[language]
        except KeyError:
            raise KeyError('Language {!r} is not defined for docstyle {!r}.'
                           .format(language, docstyle))

        metadata_settings = ('param_start', 'param_end', 'return_sep')

        metadata = cls.Metadata(*(str(docstyle_settings.get(req_setting, ''))
                                  for req_setting in metadata_settings))

        marker_sets = (tuple(value)
                       for key, value in
                       docstyle_settings.contents.items()
                       if key not in metadata_settings and
                       not key.startswith('comment'))

        return cls(language, docstyle, marker_sets, metadata)
开发者ID:RohanVB,项目名称:coala,代码行数:64,代码来源:DocstyleDefinition.py

示例8: ConfWriterTest

# 需要导入模块: from coalib.parsing.ConfParser import ConfParser [as 别名]
# 或者: from coalib.parsing.ConfParser.ConfParser import parse [as 别名]
class ConfWriterTest(unittest.TestCase):
    example_file = ('to be ignored \n'
                    '    save=true\n'
                    '    a_default, another = val \n'
                    '    TEST = tobeignored  # thats a comment \n'
                    '    test = push \n'
                    '    t = \n'
                    '    [Section] \n'
                    '    [MakeFiles] \n'
                    '     j  , ANother = a \n'
                    '                   multiline \n'
                    '                   value \n'
                    '    ; just a omment \n'
                    '    ; just a omment \n'
                    '    key\\ space = value space\n'
                    '    key\\=equal = value=equal\n'
                    '    key\\\\backslash = value\\\\backslash\n'
                    '    key\\,comma = value,comma\n'
                    '    key\\#hash = value\\#hash\n'
                    '    key\\.dot = value.dot\n')

    def setUp(self):
        self.file = os.path.join(tempfile.gettempdir(), 'ConfParserTestFile')
        with open(self.file, 'w', encoding='utf-8') as file:
            file.write(self.example_file)

        self.conf_parser = ConfParser()
        self.write_file_name = os.path.join(tempfile.gettempdir(),
                                            'ConfWriterTestFile')
        self.uut = ConfWriter(self.write_file_name)

    def tearDown(self):
        self.uut.close()
        os.remove(self.file)
        os.remove(self.write_file_name)

    def test_exceptions(self):
        self.assertRaises(TypeError, self.uut.write_section, 5)

    def test_write(self):
        result_file = ['[Default]\n',
                       'save = true\n',
                       'a_default, another = val\n',
                       '# thats a comment\n',
                       'test = push\n',
                       't = \n',
                       '[Section]\n',
                       '[MakeFiles]\n',
                       'j, ANother = a\n',
                       'multiline\n',
                       'value\n',
                       '; just a omment\n',
                       '; just a omment\n',
                       'key\\ space = value space\n',
                       'key\\=equal = value=equal\n',
                       'key\\\\backslash = value\\\\backslash\n',
                       'key\\,comma = value,comma\n',
                       'key\\#hash = value\\#hash\n',
                       'key\\.dot = value.dot\n']
        self.uut.write_sections(self.conf_parser.parse(self.file))
        self.uut.close()

        with open(self.write_file_name, 'r') as f:
            lines = f.readlines()

        self.assertEqual(result_file, lines)
开发者ID:RohanVB,项目名称:coala,代码行数:68,代码来源:ConfWriterTest.py

示例9: ConfParserTest

# 需要导入模块: from coalib.parsing.ConfParser import ConfParser [as 别名]
# 或者: from coalib.parsing.ConfParser.ConfParser import parse [as 别名]
class ConfParserTest(unittest.TestCase):
    example_file = """to be ignored
    a_default, another = val
    TEST = tobeignored  # do you know that thats a comment
    test = push
    t =
    [MakeFiles]
     j  , another = a
                   multiline
                   value
    ; just a omment
    ; just a omment
    nokey. = value
    default.test = content
    makefiles.lastone = val
    """

    def setUp(self):
        self.tempdir = tempfile.gettempdir()
        self.file = os.path.join(self.tempdir, ".coafile")
        self.nonexistentfile = os.path.join(self.tempdir, "e81k7bd98t")
        with open(self.file, "w") as filehandler:
            filehandler.write(self.example_file)

        self.uut = ConfParser()
        if sys.version_info < (3, 3):
            err = OSError
        else:
            err = FileNotFoundError
        try:
            os.remove(self.nonexistentfile)
        except err:
            pass

    def tearDown(self):
        os.remove(self.file)

    def test_parse(self):
        default_should = OrderedDict([
            ('a_default', 'val'),
            ('another', 'val'),
            ('comment0', '# do you know that thats a comment'),
            ('test', 'content'),
            ('t', '')
        ])

        makefiles_should = OrderedDict([
            ('j', 'a\nmultiline\nvalue'),
            ('another', 'a\nmultiline\nvalue'),
            ('comment1', '; just a omment'),
            ('comment2', '; just a omment'),
            ('lastone', 'val'),
            ('comment3', ''),
            ('a_default', 'val'),
            ('comment0', '# do you know that thats a comment'),
            ('test', 'content'),
            ('t', '')
        ])

        self.assertRaises(self.uut.FileNotFoundError,
                          self.uut.parse,
                          self.nonexistentfile)
        sections = self.uut.parse(self.file)
        self.assertNotEqual(self.uut.parse(self.file, True), sections)

        key, val = sections.popitem(last=False)
        self.assertTrue(isinstance(val, Section))
        self.assertEqual(key, 'default')

        is_dict = OrderedDict()
        for k in val:
            is_dict[k] = str(val[k])
        self.assertEqual(is_dict, default_should)

        key, val = sections.popitem(last=False)
        self.assertTrue(isinstance(val, Section))
        self.assertEqual(key, 'makefiles')

        is_dict = OrderedDict()
        for k in val:
            is_dict[k] = str(val[k])
        self.assertEqual(is_dict, makefiles_should)

        self.assertEqual(val["comment1"].key, "comment1")

        self.assertRaises(IndexError,
                          self.uut.get_section,
                          "inexistent section")

    def test_config_directory(self):
        self.uut.parse(self.tempdir)
开发者ID:andreimacavei,项目名称:coala,代码行数:93,代码来源:ConfParserTest.py

示例10: ConfParserTest

# 需要导入模块: from coalib.parsing.ConfParser import ConfParser [as 别名]
# 或者: from coalib.parsing.ConfParser.ConfParser import parse [as 别名]
class ConfParserTest(unittest.TestCase):
    example_file = """setting = without_section
    [foo]
    to be ignored
    a_default, another = val
    TEST = tobeignored  # do you know that thats a comment
    test = push
    t =
    escaped_\\=equal = escaped_\\#hash
    escaped_\\\\backslash = escaped_\\ space
    escaped_\\,comma = escaped_\\.dot
    [MakeFiles]
     j  , another = a
                   multiline
                   value
    # just a comment
    # just a comment
    nokey. = value
    foo.test = content
    makefiles.lastone = val
    append += key

    [EMPTY_ELEM_STRIP]
    A = a, b, c
    B = a, ,, d
    C = ,,,

    [name]
    key1 = value1
    key2 = value1
    key1 = value2
    """

    def setUp(self):
        self.tempdir = tempfile.gettempdir()
        self.file = os.path.join(self.tempdir, '.coafile')
        self.nonexistentfile = os.path.join(self.tempdir, 'e81k7bd98t')
        with open(self.file, 'w') as file:
            file.write(self.example_file)

        self.uut = ConfParser()
        try:
            os.remove(self.nonexistentfile)
        except FileNotFoundError:
            pass

        logger = logging.getLogger()

        with self.assertLogs(logger, 'WARNING') as self.cm:
            self.sections = self.uut.parse(self.file)

    def tearDown(self):
        os.remove(self.file)

    def test_warning_typo(self):
        logger = logging.getLogger()
        with self.assertLogs(logger, 'WARNING') as cm:
            newConf = ConfParser(comment_seperators=('#',))
            self.assertEquals(cm.output[0], 'WARNING:root:The setting '
                              '`comment_seperators` is deprecated. '
                              'Please use `comment_separators` '
                              'instead.')

    def test_parse_nonexisting_file(self):
        self.assertRaises(FileNotFoundError,
                          self.uut.parse,
                          self.nonexistentfile)
        self.assertNotEqual(self.uut.parse(self.file, True), self.sections)

    def test_parse_nonexisting_section(self):
        self.assertRaises(IndexError,
                          self.uut.get_section,
                          'non-existent section')

    def test_parse_default_section_deprecated(self):
        default_should = OrderedDict([
            ('setting', 'without_section')])

        key, val = self.sections.popitem(last=False)
        self.assertTrue(isinstance(val, Section))
        self.assertEqual(key, 'default')

        is_dict = OrderedDict()
        for k in val:
            is_dict[k] = str(val[k])
        self.assertEqual(is_dict, default_should)

        self.assertRegex(self.cm.output[0],
                         'A setting does not have a section.')

        # Check if line number is correctly set when
        # no section is given
        line_num = val.contents['setting'].line_number
        self.assertEqual(line_num, 1)

    def test_parse_foo_section(self):
        foo_should = OrderedDict([
            ('a_default', 'val'),
            ('another', 'val'),
            ('comment0', '# do you know that thats a comment'),
#.........这里部分代码省略.........
开发者ID:Anmolbansal1,项目名称:coala,代码行数:103,代码来源:ConfParserTest.py

示例11: ConfParserTest

# 需要导入模块: from coalib.parsing.ConfParser import ConfParser [as 别名]
# 或者: from coalib.parsing.ConfParser.ConfParser import parse [as 别名]
class ConfParserTest(unittest.TestCase):
    example_file = """to be ignored
    a_default, another = val
    TEST = tobeignored  # do you know that thats a comment
    test = push
    t =
    [MakeFiles]
     j  , another = a
                   multiline
                   value
    # just a omment
    # just a omment
    nokey. = value
    default.test = content
    makefiles.lastone = val

    [EMPTY_ELEM_STRIP]
    A = a, b, c
    B = a, ,, d
    C = ,,,
    """

    def setUp(self):
        self.tempdir = tempfile.gettempdir()
        self.file = os.path.join(self.tempdir, ".coafile")
        self.nonexistentfile = os.path.join(self.tempdir, "e81k7bd98t")
        with open(self.file, "w") as filehandler:
            filehandler.write(self.example_file)

        self.uut = ConfParser()
        try:
            os.remove(self.nonexistentfile)
        except FileNotFoundError:
            pass

        self.sections = self.uut.parse(self.file)

    def tearDown(self):
        os.remove(self.file)

    def test_parse_nonexisting_file(self):
        self.assertRaises(FileNotFoundError,
                          self.uut.parse,
                          self.nonexistentfile)
        self.assertNotEqual(self.uut.parse(self.file, True), self.sections)

    def test_parse_nonexisting_section(self):
        self.assertRaises(IndexError,
                          self.uut.get_section,
                          "inexistent section")

    def test_parse_default_section(self):
        default_should = OrderedDict([
            ('a_default', 'val'),
            ('another', 'val'),
            ('comment0', '# do you know that thats a comment'),
            ('test', 'content'),
            ('t', '')])

        key, val = self.sections.popitem(last=False)
        self.assertTrue(isinstance(val, Section))
        self.assertEqual(key, 'default')

        is_dict = OrderedDict()
        for k in val:
            is_dict[k] = str(val[k])
        self.assertEqual(is_dict, default_should)

    def test_parse_makefiles_section(self):
        makefiles_should = OrderedDict([
            ('j', 'a\nmultiline\nvalue'),
            ('another', 'a\nmultiline\nvalue'),
            ('comment1', '# just a omment'),
            ('comment2', '# just a omment'),
            ('lastone', 'val'),
            ('comment3', ''),
            ('a_default', 'val'),
            ('comment0', '# do you know that thats a comment'),
            ('test', 'content'),
            ('t', '')])

        # Pop off the default section.
        self.sections.popitem(last=False)

        key, val = self.sections.popitem(last=False)
        self.assertTrue(isinstance(val, Section))
        self.assertEqual(key, 'makefiles')

        is_dict = OrderedDict()
        for k in val:
            is_dict[k] = str(val[k])
        self.assertEqual(is_dict, makefiles_should)

        self.assertEqual(val["comment1"].key, "comment1")

    def test_parse_empty_elem_strip_section(self):
        empty_elem_strip_should = OrderedDict([
            ('a', 'a, b, c'),
            ('b', 'a, ,, d'),
            ('c', ',,,'),
#.........这里部分代码省略.........
开发者ID:Tanmay28,项目名称:coala,代码行数:103,代码来源:ConfParserTest.py

示例12: ConfParserTest

# 需要导入模块: from coalib.parsing.ConfParser import ConfParser [as 别名]
# 或者: from coalib.parsing.ConfParser.ConfParser import parse [as 别名]
class ConfParserTest(unittest.TestCase):
    example_file = """to be ignored
    a_default, another = val
    TEST = tobeignored  # do you know that thats a comment
    test = push
    t =
    [MakeFiles]
     j  , another = a
                   multiline
                   value
    # just a omment
    # just a omment
    nokey. = value
    default.test = content
    makefiles.lastone = val
    """

    def setUp(self):
        self.tempdir = tempfile.gettempdir()
        self.file = os.path.join(self.tempdir, ".coafile")
        self.nonexistentfile = os.path.join(self.tempdir, "e81k7bd98t")
        with open(self.file, "w") as filehandler:
            filehandler.write(self.example_file)

        self.uut = ConfParser()
        try:
            os.remove(self.nonexistentfile)
        except FileNotFoundError:
            pass

    def tearDown(self):
        os.remove(self.file)

    def test_parse(self):
        default_should = OrderedDict(
            [
                ("a_default", "val"),
                ("another", "val"),
                ("comment0", "# do you know that thats a comment"),
                ("test", "content"),
                ("t", ""),
            ]
        )

        makefiles_should = OrderedDict(
            [
                ("j", "a\nmultiline\nvalue"),
                ("another", "a\nmultiline\nvalue"),
                ("comment1", "# just a omment"),
                ("comment2", "# just a omment"),
                ("lastone", "val"),
                ("comment3", ""),
                ("a_default", "val"),
                ("comment0", "# do you know that thats a comment"),
                ("test", "content"),
                ("t", ""),
            ]
        )

        self.assertRaises(FileNotFoundError, self.uut.parse, self.nonexistentfile)
        sections = self.uut.parse(self.file)
        self.assertNotEqual(self.uut.parse(self.file, True), sections)

        key, val = sections.popitem(last=False)
        self.assertTrue(isinstance(val, Section))
        self.assertEqual(key, "default")

        is_dict = OrderedDict()
        for k in val:
            is_dict[k] = str(val[k])
        self.assertEqual(is_dict, default_should)

        key, val = sections.popitem(last=False)
        self.assertTrue(isinstance(val, Section))
        self.assertEqual(key, "makefiles")

        is_dict = OrderedDict()
        for k in val:
            is_dict[k] = str(val[k])
        self.assertEqual(is_dict, makefiles_should)

        self.assertEqual(val["comment1"].key, "comment1")

        self.assertRaises(IndexError, self.uut.get_section, "inexistent section")

    def test_config_directory(self):
        self.uut.parse(self.tempdir)
开发者ID:VCTLabs,项目名称:coala,代码行数:89,代码来源:ConfParserTest.py


注:本文中的coalib.parsing.ConfParser.ConfParser.parse方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。