Skip to content

Commit

Permalink
fix: issue with uncaught UnicodeDecodeError
Browse files Browse the repository at this point in the history
Even though, there are methods to safely get the json from file, string,
or url even, there is no surely that people will not pass their own data
into the json2xml.Json2xml() contructor.

However, if the data is corrupt or mal-formed, there is a chance an
exception can be raised, brining the program to a halt.

Hence, a new error type is introduced, that protects against it and
raises InvalidDataError exception which can that be caught and logged in
a program that uses Json2xml.

- Github Issue: #106

Authored-by: Vinit Kumar <mail@vinitkumar.me>
Signed-off-by: Vinit Kumar <mail@vinitkumar.me>
  • Loading branch information
vinitkumar committed Feb 10, 2022
1 parent 8a996f1 commit a9cd75b
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 2 deletions.
9 changes: 8 additions & 1 deletion json2xml/json2xml.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import xml
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 +36,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

0 comments on commit a9cd75b

Please sign in to comment.