Reputation: 30121
Right now I'm just checking the response of the link like so:
self.client = Client()
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
Is there a Django-ic way to test a link to see if a file download event actually takes place? Can't seem to find much resource on this topic.
Upvotes: 40
Views: 14252
Reputation: 6189
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()
Upvotes: 2
Reputation: 16071
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"
)
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()
Upvotes: 59