Mohamed Ibrahim
Mohamed Ibrahim

Reputation: 225

How to test file upload in pytest?

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

Upvotes: 2

Views: 4661

Answers (2)

Sezer BOZKIR
Sezer BOZKIR

Reputation: 562

You can use it mock library for testing file upload;

from unittest.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

Upvotes: 2

May.D
May.D

Reputation: 1910

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

Upvotes: 1

Related Questions