From e51a9012fdbadb95333e49a49eeda50d64a949ff Mon Sep 17 00:00:00 2001 From: Patrick Smith Date: Wed, 23 Jan 2019 10:30:30 -0500 Subject: [PATCH] Add custom JSON encoder to handle attachment objects --- atst/utils/json.py | 9 +++++++++ tests/utils/test_json.py | 15 +++++++++++++++ 2 files changed, 24 insertions(+) create mode 100644 atst/utils/json.py create mode 100644 tests/utils/test_json.py diff --git a/atst/utils/json.py b/atst/utils/json.py new file mode 100644 index 00000000..a489fcaa --- /dev/null +++ b/atst/utils/json.py @@ -0,0 +1,9 @@ +from flask.json import JSONEncoder +from atst.models.attachment import Attachment + + +class CustomJSONEncoder(JSONEncoder): + def default(self, obj): + if isinstance(obj, Attachment): + return obj.filename + return JSONEncoder.default(self, obj) diff --git a/tests/utils/test_json.py b/tests/utils/test_json.py new file mode 100644 index 00000000..5db25c17 --- /dev/null +++ b/tests/utils/test_json.py @@ -0,0 +1,15 @@ +import json +from atst.utils.json import CustomJSONEncoder + +from tests.factories import AttachmentFactory + + +encoder = CustomJSONEncoder() + + +def test_custom_encoder_serializes_attachments(): + filename = "jar_jar_is_secretly_a_sith_lord.pdf" + attachment = AttachmentFactory.create(filename=filename) + encoded = encoder.encode({"file": attachment}) + expected = json.dumps({"file": filename}) + assert encoded == expected