Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: issue with uncaught UnicodeDecodeError #107

Merged
merged 3 commits into from
Feb 10, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion json2xml/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

__author__ = """Vinit Kumar"""
__email__ = "mail@vinitkumar.me"
__version__ = "3.12.0"
__version__ = "3.14.0"


# from .utils import readfromurl, readfromstring, readfromjson
8 changes: 7 additions & 1 deletion json2xml/json2xml.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from typing import Optional, Any
from defusedxml.minidom import parseString
from pyexpat import ExpatError
from json2xml import dicttoxml
from .utils import InvalidDataError


class Json2xml:
Expand Down Expand Up @@ -33,6 +35,10 @@ def to_xml(self) -> Optional[Any]:
item_wrap=self.item_wrap,
)
if self.pretty:
return parseString(xml_data).toprettyxml()
try:
result = parseString(xml_data).toprettyxml()
except ExpatError as e:
raise InvalidDataError
return result
return xml_data
return None
2 changes: 2 additions & 0 deletions json2xml/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
class JSONReadError(Exception):
pass

class InvalidDataError(Exception):
pass

class URLReadError(Exception):
pass
Expand Down
8 changes: 7 additions & 1 deletion tests/test_json2xml.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

from json2xml import json2xml
from json2xml.dicttoxml import dicttoxml
from json2xml.utils import readfromjson, readfromstring, readfromurl, JSONReadError, StringReadError, URLReadError
from json2xml.utils import InvalidDataError, readfromjson, readfromstring, readfromurl, JSONReadError, StringReadError, URLReadError


class TestJson2xml(unittest.TestCase):
Expand Down Expand Up @@ -163,3 +163,9 @@ def test_dict2xml_with_custom_root(self):
payload = {'mock': 'payload'}
result = dicttoxml(payload, attr_type=False, custom_root="element")
assert b'<?xml version="1.0" encoding="UTF-8" ?><element><mock>payload</mock></element>' == result

def test_bad_data(self):
data = b"!\0a\8f".decode("utf-8")
with pytest.raises(InvalidDataError) as pytest_wrapped_e:
result = json2xml.Json2xml(data).to_xml()
assert pytest_wrapped_e.type == InvalidDataError