用于测试文件下载的Django Unit Test

sup*_*er9 23 django unit-testing

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

self.client = Client()
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
Run Code Online (Sandbox Code Playgroud)

是否有一种Django-ic方式来测试链接,看看文件下载事件是否真的发生了?似乎无法在这个主题上找到太多资源.

hwj*_*wjp 30

如果url旨在生成文件而不是"正常"http响应,那么它content-type和/或content-disposition将是不同的.

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

self.assertEquals(
    response.get('Content-Disposition'),
    "attachment; filename=mypic.jpg"
)
Run Code Online (Sandbox Code Playgroud)

更多信息: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()
Run Code Online (Sandbox Code Playgroud)