我在 Django 模板测试中有一个奇怪的问题。当测试执行我的 View 时, View 返回一个 HttpResponse 对象。但是,当我将该响应对象传递给 Django TestCase assertContains 方法时,响应对象变成了一个字符串。由于该字符串没有像响应对象那样的“status_code”属性,因此测试失败。这是我的代码:
模板测试.py
from django.test import TestCase
from django.test.client import RequestFactory
class TestUploadMainPhotoTemplate(TestCase):
def setUp(self):
self.factory = RequestFactory()
def test_user_selects_non_jpeg_photo_file(self):
"""
User is trying to upload a photo file via a form
with an ImageField. However, the file doesn't have
a '.jpg' extension so the form's is_valid function, which
I've overridden, flags this as an error and returns False.
"""
with open('photo.png') as test_photo:
request = self.factory.post(reverse('upload-photo'),
{'upload_photo': '[Upload Photo]',
'photo': test_photo})
kwargs = {'template': 'upload_photo.html'}
response = upload_photo(request, **kwargs)
# pdb.set_trace()
self.assertContains(response, 'Error: photo file must be a JPEG file')
当我在调试器中运行此代码并在调用 assertContains 之前执行“type(response)”时,我可以看到“response”是一个 HttpResponse 对象。但是,当调用 assertContains 时,我收到此错误:
AttributeError: 'str' object has no attribute 'status_code'
我在位置 .../django/test/testcases.py:638 的 assertContains 方法中设置了一个额外的断点:
self.assertEqual(response.status_code, status_code...
此时,当我再次执行 'type(response)' 时,我看到它已成为一个字符串对象并且没有 status_code 属性。谁能解释发生了什么?我已经在其他十几个模板测试中成功地使用了相同的测试模式,并且它在所有这些测试中都有效。这可能与此测试涉及上传文件这一事实有关吗?
谢谢。
最佳答案
我有一个类似的问题并通过查看 assertContains 解决了它,它并没有真正帮助你,但谁知道呢?
void assertContains( SimpleTestCase self, WSGIRequest response, text, count = ..., int status_code = ..., string msg_prefix = ..., bool html = ... )
断言响应指示检索到某些内容
成功,(即 HTTP 状态代码符合预期),并且
text
发生 count
响应内容中的次数。如果
count
为无,计数无关紧要 - 断言为真如果文本在响应中至少出现一次。
Could it have something to do with the fact that this test involves uploading a file?
当然,因为我成功地为一个简单的 HttpResponse 编写了测试:
response = self.client.get('/administration/', follow=True)
self.assertContains(response, '<link href="/static/css/bootstrap.min.css" rel="stylesheet">',msg_prefix="The page should use Bootstrap")
所以我并没有真正帮助,但也许这可以帮助一些人。
关于django - HttpResponse 对象在传递给 assertContains 时变为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19911673/