0

I have a django test method that is supposed to test that the correct image was returned in an httpresponse. Here is the code for the test:

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)

The test isn't working because I'm comparing the opened image with the entire http response instead of just the image it has. I've tried to access the image by checking for fields it may have but it doesn't appear to have any. In the view I'm returning the image using HttpResponse(image_data, content_type="image/jpg") and from looking at the fields from the class in the docs I'm not seeing a field that would return the image. How can I access the image from the httpresponse so that it can be tested?

Falko
  • 17,076
  • 13
  • 60
  • 105
loremIpsum1771
  • 2,497
  • 5
  • 40
  • 87
  • can you compare two files instead of images ? If it is the path you want to compare you can return the url of the image file and then compare it. Otherwise can you compare two files ? I haven't seen an image returning in the response any time. – Chintan Joshi Mar 15 '18 at 05:21
  • There are a handful of examples out there of getting images from requests: https://gist.github.com/FZambia/faab8f811dee95c7b174 , https://stackoverflow.com/questions/16174022/download-a-remote-image-and-save-it-to-a-django-model – Gerik Mar 15 '18 at 05:48

1 Answers1

1

Since you mention that you're writing the image to HttpResponse, you can extract the image from response.content in your tests.

Here's an example with comments for more explanation:

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())
xyres
  • 20,487
  • 3
  • 56
  • 85