用于测试文件下载的Django Unit Test [英] Django Unit Test for testing a file download

查看:135
本文介绍了用于测试文件下载的Django Unit Test的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我只是检查链接的响应,如下所示:

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)

有没有Django-ic方式来测试一个链接,看看文件下载事件是否真的发生?似乎找不到这个主题的资源。

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.

推荐答案

如果url是为了生成一个文件而不是一个正常的http响应,那么其内容类型和/或 content-disposition 将不同。

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

更多信息:
https://docs.djangoproject.com/en/dev/ref/request-response/#telling-the-browser-to-对待作为文件的附件

UPD:
如果要读取附件文件的实际内容,你可以使用response.content。一个zip文件的例子:

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 = StringIO.StringIO(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()

这篇关于用于测试文件下载的Django Unit Test的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆