2011-11-23 65 views
18

现在我只是检查链接的,像这样的回应:Django的单元测试用于测试文件下载

self.client = Client() 
response = self.client.get(url) 
self.assertEqual(response.status_code, 200) 

有测试链路,看看文件下载一个Django-IC方式事件实际发生?似乎无法找到有关此主题的很多资源。

回答

22

如果网址是为了生成文件而不是“普通”http响应,那么它的content-type和/或content-disposition将会不同。

响应对象基本上是一个字典,所以你可以这么像

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

更多信息: https://docs.djangoproject.com/en/dev/ref/request-response/#telling-the-browser-to-treat-the-response-as-a-file-attachment

UPD: 如果你想阅读的附加文件的实际内容,你可以使用response.content。一个zip文件示例:

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

是的,但你无法控制下载的文件... – francois

+0

你的意思是你要检查该文件的实际内容?你可以使用'response.content' - https://docs.djangoproject.com/en/dev/ref/request-response/#id4 – hwjp

+1

我正在尝试做这个确切的事情,但得到错误“ValueError:I/O操作在关闭的文件“每当我做任何事情与response.content,甚至传递给StringIO。 –