From 360a94c4a3745dfe59863c6a112acf8bcf38840d Mon Sep 17 00:00:00 2001 From: Daniel Mach Date: Mon, 3 Jun 2024 08:21:17 +0200 Subject: [PATCH] Fix config parser to throw an exception on duplicate sections or options --- osc/OscConfigParser.py | 8 ++++++-- tests/test_config_parser.py | 23 +++++++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/osc/OscConfigParser.py b/osc/OscConfigParser.py index 519a4722..eef3a446 100644 --- a/osc/OscConfigParser.py +++ b/osc/OscConfigParser.py @@ -263,7 +263,9 @@ class OscConfigParser(configparser.ConfigParser): 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 @@ -294,7 +296,9 @@ class OscConfigParser(configparser.ConfigParser): 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) diff --git a/tests/test_config_parser.py b/tests/test_config_parser.py index 102e89d3..c75ff350 100644 --- a/tests/test_config_parser.py +++ b/tests/test_config_parser.py @@ -1,3 +1,4 @@ +import configparser import unittest from osc.OscConfigParser import OscConfigParser @@ -21,6 +22,28 @@ pass= # 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()