Skip to content

Commit

Permalink
🐛 Fix parse_it when given Mapping contains unattended types (#51)
Browse files Browse the repository at this point in the history
  • Loading branch information
Ousret authored Oct 23, 2023
1 parent f06abea commit fe18870
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 2 deletions.
3 changes: 2 additions & 1 deletion kiss_headers/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))

Expand Down
9 changes: 9 additions & 0 deletions kiss_headers/utils.py
Original file line number Diff line number Diff line change
@@ -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

Expand Down Expand Up @@ -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
2 changes: 1 addition & 1 deletion kiss_headers/version.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@
Expose version
"""

__version__ = "2.4.1"
__version__ = "2.4.2"
VERSION = __version__.split(".")
32 changes: 32 additions & 0 deletions tests/test_from_unknown_mapping.py
Original file line number Diff line number Diff line change
@@ -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]')

0 comments on commit fe18870

Please sign in to comment.