【问题标题】:Accessing an image in an httpresponse在 httpresponse 中访问图像
【发布时间】:2018-03-15 05:02:35
【问题描述】:

我有一个 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 访问图像以便对其进行测试?

【问题讨论】:

标签: python django http file-io


【解决方案1】:

由于您提到要将图像写入HttpResponse,因此您可以在测试中从response.content提取图像。

下面是一个带有 cmets 的示例以获得更多解释:

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())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 2016-04-19
    • 2011-12-21
    相关资源
    最近更新 更多