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