Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Unit Test for testing a file download

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.

like image 406
super9 Avatar asked Nov 23 '11 14:11

super9


1 Answers

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()
like image 199
hwjp Avatar answered Sep 24 '22 23:09

hwjp