如何在pytest中测试文件上传?

问题描述 投票:0回答:2

如何在使用 json.dumps 时序列化文件对象?

我正在使用 pytest 在 django 中测试文件上传,我有这个功能

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",
    )

我尝试将

file_content
设置为字节对象,但收到此错误
TypeError: Object of type bytes is not JSON serializable
我需要将整个文件作为 json 序列化发送到我的端点

python django pytest
2个回答
2
投票

您可以使用它的模拟库来测试文件上传;

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",
    )

详细的另一个答案; 如何在 django 中对文件上传进行单元测试


1
投票

您的 API 端点需要包含文件的多部分表单。下面是我用来从本地文件发送多部分表单进行测试的函数。如果您已经有文件字节,请跳过

open
行并仅在
file_content
中使用
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
© www.soinside.com 2019 - 2024. All rights reserved.