From 3cfc5e3e3ce9e2e01b2d00ad30ee4b34499af443 Mon Sep 17 00:00:00 2001 From: Kelly Brazil Date: Fri, 9 Feb 2024 17:13:19 -0800 Subject: [PATCH] fix ini parser for edge cases with non-value keys --- jc/parsers/ini.py | 25 ++++++++++++------------- tests/test_ini.py | 9 +++++++++ 2 files changed, 21 insertions(+), 13 deletions(-) diff --git a/jc/parsers/ini.py b/jc/parsers/ini.py index 64d5ae66..21ce3cf4 100644 --- a/jc/parsers/ini.py +++ b/jc/parsers/ini.py @@ -75,7 +75,7 @@ import uuid class info(): """Provides parser metadata (version, author, etc.)""" - version = '2.1' + version = '2.2' description = 'INI file parser' author = 'Kelly Brazil' author_email = 'kellyjonbrazil@gmail.com' @@ -87,14 +87,10 @@ class info(): __version__ = info.version -class MyDict(dict): - def __setitem__(self, key, value): - # convert None values to empty string - if value is None: - self[key] = '' - - else: - super().__setitem__(key, value) +def _none_to_empty_string(data): + if data is None: + return '' + return data def _process(proc_data): @@ -110,13 +106,18 @@ def _process(proc_data): Dictionary representing the INI file. """ # remove quotation marks from beginning and end of values + # and convert None to empty string for k, v in proc_data.items(): if isinstance(v, dict): for key, value in v.items(): - v[key] = jc.utils.remove_quotes(value) + value = _none_to_empty_string(value) + value = jc.utils.remove_quotes(value) + v[key] = value continue - proc_data[k] = jc.utils.remove_quotes(v) + v = _none_to_empty_string(v) + v = jc.utils.remove_quotes(v) + proc_data[k] = v return proc_data @@ -143,7 +144,6 @@ def parse(data, raw=False, quiet=False): if jc.utils.has_data(data): ini_parser = configparser.ConfigParser( - dict_type = MyDict, allow_no_value=True, interpolation=None, default_section=None, @@ -175,4 +175,3 @@ def parse(data, raw=False, quiet=False): raw_output.update(temp_dict) return raw_output if raw else _process(raw_output) - diff --git a/tests/test_ini.py b/tests/test_ini.py index 43362faa..2604a4f5 100644 --- a/tests/test_ini.py +++ b/tests/test_ini.py @@ -104,6 +104,15 @@ key5 = "quoted" """ self.assertEqual(jc.parsers.ini.parse(self.generic_ini_single_quote, quiet=True), self.generic_ini_single_quote_json) + def test_ini_single_key_no_value(self): + """ + Test ini file with a single item with no value. This caused issues in jc v.1.25.0 + """ + data = '''[data] +novalue +''' + expected = {"data":{"novalue":""}} + self.assertEqual(jc.parsers.ini.parse(data, quiet=True), expected) if __name__ == '__main__':