我在 Django 模板测试中有一个奇怪的问题。当测试执行我的视图时,视图返回一个 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 属性。谁能解释发生了什么?我已经在其他十几个模板测试中成功地使用了相同的测试模式,并且它在所有这些测试中都有效。这可能与此测试涉及上传文件这一事实有关吗?
谢谢。