简体   繁体   中英

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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM