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

feat: Ignore malformed json files in transformer #750

Merged
merged 1 commit into from
Feb 21, 2023
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
10 changes: 7 additions & 3 deletions tests/codegen/test_transformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,14 +133,15 @@ def test_process_xml_documents(
mock_map.assert_has_calls([mock.call(x, "foo") for x in elements])
mock_reduce_classes.assert_called_once_with(classes_a + classes_c)

@mock.patch("xsdata.codegen.transformer.logger.warning")
@mock.patch.object(ClassUtils, "reduce_classes")
@mock.patch.object(DictMapper, "map")
@mock.patch.object(SchemaTransformer, "load_resource")
def test_process_json_documents(
self, mock_load_resource, mock_map, mock_reduce_classes
self, mock_load_resource, mock_map, mock_reduce_classes, mock_warning
):
uris = ["foo/a.json", "foo/b.json", "foo/c.json"]
resources = [b'{"foo": 1}', None, b'[{"foo": true}]']
uris = ["foo/a.json", "foo/b.json", "foo/c.json", "bar.json"]
resources = [b'{"foo": 1}', None, b'[{"foo": true}]', b"notjson"]

classes_a = ClassFactory.list(2)
classes_c = ClassFactory.list(3)
Expand All @@ -161,6 +162,9 @@ def test_process_json_documents(
]
)
mock_reduce_classes.assert_called_once_with(classes_a + classes_c)
mock_warning.assert_called_once_with(
"JSON load failed for file: %s", uris[3], exc_info=mock.ANY
)

@mock.patch.object(DtdMapper, "map")
@mock.patch.object(DtdParser, "parse")
Expand Down
17 changes: 10 additions & 7 deletions xsdata/codegen/transformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,13 +174,16 @@ def process_json_documents(self, uris: List[str]):
for uri in uris:
input_stream = self.load_resource(uri)
if input_stream:
data = json.load(io.BytesIO(input_stream))
logger.info("Parsing document %s", uri)
if isinstance(data, dict):
data = [data]

for obj in data:
classes.extend(DictMapper.map(obj, name, dirname))
try:
data = json.load(io.BytesIO(input_stream))
logger.info("Parsing document %s", uri)
if isinstance(data, dict):
data = [data]

for obj in data:
classes.extend(DictMapper.map(obj, name, dirname))
except ValueError as exc:
logger.warning("JSON load failed for file: %s", uri, exc_info=exc)

self.classes.extend(ClassUtils.reduce_classes(classes))

Expand Down