2011-11-23 79 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。 –