Skip to content

Commit a9cd75b

Browse files
committed
fix: issue with uncaught UnicodeDecodeError
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>
1 parent 8a996f1 commit a9cd75b

File tree

3 files changed

+17
-2
lines changed

3 files changed

+17
-2
lines changed

json2xml/json2xml.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
1+
import xml
12
from typing import Optional, Any
23
from defusedxml.minidom import parseString
4+
from pyexpat import ExpatError
35
from json2xml import dicttoxml
6+
from .utils import InvalidDataError
47

58

69
class Json2xml:
@@ -33,6 +36,10 @@ def to_xml(self) -> Optional[Any]:
3336
item_wrap=self.item_wrap,
3437
)
3538
if self.pretty:
36-
return parseString(xml_data).toprettyxml()
39+
try:
40+
result = parseString(xml_data).toprettyxml()
41+
except ExpatError as e:
42+
raise InvalidDataError
43+
return result
3744
return xml_data
3845
return None

json2xml/utils.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
class JSONReadError(Exception):
88
pass
99

10+
class InvalidDataError(Exception):
11+
pass
1012

1113
class URLReadError(Exception):
1214
pass

tests/test_json2xml.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313

1414
from json2xml import json2xml
1515
from json2xml.dicttoxml import dicttoxml
16-
from json2xml.utils import readfromjson, readfromstring, readfromurl, JSONReadError, StringReadError, URLReadError
16+
from json2xml.utils import InvalidDataError, readfromjson, readfromstring, readfromurl, JSONReadError, StringReadError, URLReadError
1717

1818

1919
class TestJson2xml(unittest.TestCase):
@@ -163,3 +163,9 @@ def test_dict2xml_with_custom_root(self):
163163
payload = {'mock': 'payload'}
164164
result = dicttoxml(payload, attr_type=False, custom_root="element")
165165
assert b'<?xml version="1.0" encoding="UTF-8" ?><element><mock>payload</mock></element>' == result
166+
167+
def test_bad_data(self):
168+
data = b"!\0a\8f".decode("utf-8")
169+
with pytest.raises(InvalidDataError) as pytest_wrapped_e:
170+
result = json2xml.Json2xml(data).to_xml()
171+
assert pytest_wrapped_e.type == InvalidDataError

0 commit comments

Comments
 (0)