From fe18870485bbfedf5a98359f8f885c43a103049c Mon Sep 17 00:00:00 2001 From: TAHRI Ahmed R Date: Mon, 23 Oct 2023 13:39:24 +0200 Subject: [PATCH] :bug: Fix parse_it when given Mapping contains unattended types (#51) --- kiss_headers/models.py | 3 ++- kiss_headers/utils.py | 9 +++++++++ kiss_headers/version.py | 2 +- tests/test_from_unknown_mapping.py | 32 ++++++++++++++++++++++++++++++ 4 files changed, 44 insertions(+), 2 deletions(-) create mode 100644 tests/test_from_unknown_mapping.py diff --git a/kiss_headers/models.py b/kiss_headers/models.py index 266b160..1e2f556 100644 --- a/kiss_headers/models.py +++ b/kiss_headers/models.py @@ -1224,7 +1224,8 @@ def __init__(self, members: List[str]): for member, index in zip(members, range(0, len(members))): if member == "": continue - + if isinstance(member, str) is False: + member = str(member) if "=" in member: key, value = tuple(member.split("=", maxsplit=1)) diff --git a/kiss_headers/utils.py b/kiss_headers/utils.py index 31b2037..afeebfc 100644 --- a/kiss_headers/utils.py +++ b/kiss_headers/utils.py @@ -1,4 +1,5 @@ from email.header import decode_header +from json import dumps from re import findall, search, sub from typing import Any, Iterable, List, Optional, Set, Tuple, Type, Union @@ -469,10 +470,18 @@ def transform_possible_encoded( decoded = [] for k, v in headers: + # we shall discard it if set to None. + if v is None: + continue if isinstance(k, bytes): k = k.decode("utf_8") if isinstance(v, bytes): v = v.decode("utf_8") + elif isinstance(v, str) is False: + if isinstance(v, (dict, list)): + v = dumps(v) + else: + v = str(v) decoded.append((k, v)) return decoded diff --git a/kiss_headers/version.py b/kiss_headers/version.py index a005319..f2b4cfb 100644 --- a/kiss_headers/version.py +++ b/kiss_headers/version.py @@ -2,5 +2,5 @@ Expose version """ -__version__ = "2.4.1" +__version__ = "2.4.2" VERSION = __version__.split(".") diff --git a/tests/test_from_unknown_mapping.py b/tests/test_from_unknown_mapping.py new file mode 100644 index 0000000..4271225 --- /dev/null +++ b/tests/test_from_unknown_mapping.py @@ -0,0 +1,32 @@ +import unittest + +from kiss_headers import parse_it + + +class UnknownMappingTest(unittest.TestCase): + def test_parse_with_bytes(self): + headers = parse_it({"User-Agent": b"Hello!"}) + + self.assertTrue("User-Agent" in headers) + + def test_parse_with_None(self): + headers = parse_it({"User-Agent": None, "Test": "Hello!"}) + + self.assertTrue("User-Agent" not in headers) + self.assertTrue("Test" in headers) + + def test_with_type_madness(self): + headers = parse_it( + { + "User-Agent": b"Hello!", + "Age": 30, + "Type": 1.554, + "BeCrazy": {"pff!": "?"}, + "Again": ["a", 0, 8, -1], + } + ) + + self.assertTrue("User-Agent" in headers) + self.assertTrue(headers.get("User-agent").content == "Hello!") + self.assertTrue(headers.get("Age").content == "30") + self.assertTrue(headers.get("Again").content == '["a", 0, 8, -1]')