Skip to content

Commit

Permalink
Merge pull request #1572 from dmach/conf-duplicate-sections
Browse files Browse the repository at this point in the history
Fix config parser to throw an exception on duplicate sections or options
  • Loading branch information
dmach authored Jun 3, 2024
2 parents d92f267 + 360a94c commit 84524b5
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
8 changes: 6 additions & 2 deletions osc/OscConfigParser.py
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,9 @@ def _read(self, fp, fpname):
mo = self.SECTCRE.match(line)
if mo:
sectname = mo.group('header')
if sectname in self._sections:
if self._strict and sectname in self._sections:
raise configparser.DuplicateSectionError(sectname, fpname, lineno)
elif sectname in self._sections:
cursect = self._sections[sectname]
elif sectname == configparser.DEFAULTSECT:
cursect = self._defaults
Expand Down Expand Up @@ -294,7 +296,9 @@ def _read(self, fp, fpname):
if optval == '""':
optval = ''
optname = self.optionxform(optname.rstrip())
if cursect == configparser.DEFAULTSECT:
if self._strict and optname in self._sections[cursect]:
raise configparser.DuplicateOptionError(sectname, optname, fpname, lineno)
elif cursect == configparser.DEFAULTSECT:
self._defaults[optname] = optval
else:
self._sections[cursect]._add_option(optname, line=line)
Expand Down
23 changes: 23 additions & 0 deletions tests/test_config_parser.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import configparser
import unittest

from osc.OscConfigParser import OscConfigParser
Expand All @@ -21,6 +22,28 @@ def test_disabled_interpolation(self):
# ValueError: invalid interpolation syntax in '%' at position 0
self.parser.set("http://localhost", "pass", "%")

def test_duplicate_section(self):
conf = """
[general]
[http://localhost]
[http://localhost]
"""
parser = OscConfigParser()
self.assertRaises(configparser.DuplicateSectionError, parser.read_string, conf)

def test_duplicate_option(self):
conf = """
[general]
[http://localhost]
user=
user=
"""
parser = OscConfigParser()
self.assertRaises(configparser.DuplicateOptionError, parser.read_string, conf)


if __name__ == "__main__":
unittest.main()

0 comments on commit 84524b5

Please sign in to comment.