django 测试文件下载 - “ValueError: I/O operation on closed file”

xor*_*xor 4 python django unit-testing

我有一个提供文件下载的视图代码,它在浏览器中运行良好。现在我正在尝试使用内部 django Client.get 为它编写一个测试:

    response = self.client.get("/compile-book/", {'id': book.id})
    self.assertEqual(response.status_code, 200)
    self.assertEquals(response.get('Content-Disposition'), 
                      "attachment; filename=book.zip")
Run Code Online (Sandbox Code Playgroud)

到目前为止,一切都很好。现在我想测试下载的文件是否是我希望它下载的文件。所以我开始说:

    f = cStringIO.StringIO(response.content)
Run Code Online (Sandbox Code Playgroud)

现在我的测试运行器响应:

Traceback (most recent call last):
  File ".../tests.py", line 154, in test_download
    f = cStringIO.StringIO(response.content)
  File "/home/epub/projects/epub-env/lib/python2.7/site-packages/django/http/response.py", line 282, in content
    self._consume_content()
  File "/home/epub/projects/epub-env/lib/python2.7/site-packages/django/http/response.py", line 278, in _consume_content
    self.content = b''.join(self.make_bytes(e) for e in self._container)   
  File "/home/epub/projects/epub-env/lib/python2.7/site-packages/django/http/response.py", line 278, in <genexpr>
    self.content = b''.join(self.make_bytes(e) for e in self._container)   
  File "/usr/lib/python2.7/wsgiref/util.py", line 30, in next 
    data = self.filelike.read(self.blksize) 
ValueError: I/O operation on closed file
Run Code Online (Sandbox Code Playgroud)

即使我只是简单地做: self.assertIsNotNone(response.content) 我得到相同的 ValueError

我能在整个互联网上找到的唯一关于测试下载的主题(包括 django 文档)是这个 stackoverflow 主题:用于测试文件下载的 Django 单元测试。尝试该解决方案导致了这些结果。对我来说,开一个新问题已经足够古老和罕见了。

有人知道在 Django 中应该如何处理下载测试吗?(顺便说一句,在 python 2.7 上运行 django 1.5)

Ris*_*nha 6

这对我们有用。我们返回,rest_framework.response.Response但它也应该与常规的 Django 响应一起使用。

import io
response = self.client.get(download_url, {'id': archive_id})
downloaded_file = io.BytesIO(b"".join(response.streaming_content))
Run Code Online (Sandbox Code Playgroud)

注意: streaming_content仅适用于StreamingHttpResponse(也适用于Django 1.10):https : //docs.djangoproject.com/en/1.10/ref/request-response/#django.http.StreamingHttpResponse.streaming_content