How to serializer a file object while using json.dumps ?
I 'm using pytest for testing file upload in django and I 've this function
def test_file_upload(self):
# file_content is a bytest object
request = client.patch(
"/fake-url/",
json.dumps({"file" : file_content}),
content_type="application/json",
)
I 've tried to set the file_content
as a bytes object but I 'm getting this error TypeError: Object of type bytes is not JSON serializable
I need to send the whole file to my endpoint as json serialized
CodePudding user response:
You can use it mock library for testing file upload;
from mock import MagicMock
from django.core.files import File
mock_image = magicMock(file=File)
mock_image.name="sample.png"
# Another test operations...
def test_file_upload(self):
# file_content is a bytest object
request = client.patch(
"/fake-url/",
{"file" : mock_image},
format="multipart",
)
Detailed another answer; how to unit test file upload in django
CodePudding user response:
Your API endpoint expects a multipart form containing file. Below is the function I use to send a multipart form from a local file for testing. If you already have file bytes, skip the open
line and just use file_content
in ContentFile
.
def send_multipart_form(self, filename):
with open(filename, "rb") as f:
file_data = ContentFile(f.read(), os.path.basename(filename))
res = self.client.put(
self.url,
data=encode_multipart(boundary=BOUNDARY, data={"file": file_data}),
content_type=MULTIPART_CONTENT,
)
return res