访问httpresponse中的图像

时间:2018-03-15 05:02:36

标签: python django http file-io

我有一个django测试方法,应该测试在httpresponse中返回正确的图像。以下是测试的代码:

   class CSStudent:
stream = 'cse'
__slots__ = ['name', 'roll']

def __init__(self, name, roll):
    self.name = name
    self.roll = roll

测试不起作用,因为我将打开的图像与整个http响应进行比较,而不仅仅是它的图像。我试图通过检查它可能具有的字段来访问该图像,但它似乎没有。在视图中,我使用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) 返回图像,并查看docs中类的字段,我没有看到会返回图像的字段。 如何从httpresponse访问图像以便对其进行测试?

1 个答案:

答案 0 :(得分:1)

由于您提到您正在将图像写入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())