访问httprespons中的图像

2024-05-14 19:06:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个django测试方法,用来测试httpresponse中是否返回了正确的图像。以下是测试代码:

c = Client()
originalFilePath = '../static_cdn/test.jpg'
image_data = open(originalFilePath, "rb")
with open(originalFilePath, "rb") as fp:
    response = c.post('/', {'image': fp})
    self.assertEqual(image_data, response)

测试不起作用,因为我将打开的映像与整个http响应进行比较,而不仅仅是它所拥有的映像。我试图通过检查图像中可能包含的字段来访问该图像,但它似乎没有任何字段。在视图中,我使用HttpResponse(image_data, content_type="image/jpg")返回图像,在查看docs中类的字段时,没有看到返回图像的字段。如何从httpresponse访问图像以便进行测试?


Tags: django图像imageclientdataresponsestaticcdn
1条回答
网友
1楼 · 发布于 2024-05-14 19:06:41

既然您提到要将图像写入HttpResponse,那么您可以在测试中从response.content提取图像。你知道吗

下面是一个带有注释的示例,以获取更多解释:

def test_returned_image_is_same_as_uploaded(self):

    # open the image
    with open('../static_cdn/test.jpg', 'rb') as f:

        # upload the image
        response = self.client.post('/', {'image': f})

        # since the file has been read once before 
        # above, you'll need to seek to beginning 
        # to be able to read it again
        f.seek(0)

        # now compare the content of the response
        # with the content of the file
        self.assertEqual(response.content, f.read())

相关问题 更多 >

    热门问题