[Django]-Django Unit Test for testing a file download

58👍

If the url is meant to produce a file rather than a “normal” http response, then its content-type and/or content-disposition will be different.

the response object is basically a dictionary, so you could so something like

self.assertEquals(
    response.get('Content-Disposition'),
    "attachment; filename=mypic.jpg"
)

more info:
https://docs.djangoproject.com/en/dev/ref/request-response/#telling-the-browser-to-treat-the-response-as-a-file-attachment

UPD:
If you want to read the actual contents of the attached file, you can use response.content. Example for a zip file:

try:
    f = io.BytesIO(response.content)
    zipped_file = zipfile.ZipFile(f, 'r')

    self.assertIsNone(zipped_file.testzip())        
    self.assertIn('my_file.txt', zipped_file.namelist())
finally:
    zipped_file.close()
    f.close()
👤hwjp

1👍

If what you are returning is a FileResponse, then you need to know that it returns a StreamingHttpResponse. If so, there’s no content on this type of response.

{AttributeError}AttributeError('This FileResponse instance has no `content` attribute. Use `streaming_content` instead.')

You need to first evaluate the entire streaming_content, and then read from the buffer.

import io

with io.BytesIO(b"".join(response.streaming_content)) as buf_bytes:
    loaded_response_content = buf_bytes.read()

Leave a comment