我有一个用于文件下载的视图代码,并且它在浏览器中运行良好。现在我尝试使用内部 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")
到目前为止,一切都很好。现在我想测试下载的文件是否是我期望下载的文件。所以我首先说:
f = cStringIO.StringIO(response.content)
现在我的测试运行者响应如下:
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
即使我简单地执行: self.assertIsNotNone(response.content) 我也会得到相同的 ValueError
The only在整个互联网(包括 django 文档)上我能找到的关于测试下载的主题是这个 stackoverflow 主题:用于测试文件下载的 Django 单元测试 https://stackoverflow.com/questions/8244220/django-unit-test-for-testing-a-file-download。尝试该解决方案导致了这些结果。它既古老又罕见,足以让我提出一个新问题。
有人知道 Django 中应该如何处理下载测试吗? (顺便说一句,在 python 2.7 上运行 django 1.5)