在测试我的Django 1.9项目期间,我收到一个错误:
Python对此代码发誓:
def test_students_list(self):
# make request to the server to get homepage page
response = self.client.get(self.url)
# do we have student name on a page?
self.assertIn('Vitaliy', response.content)
如何为函数assertIn中的参数设置相同的编码? 我试过了:
self.assertIn(u" Vitaliy",response.content.decode(' utf8'))
结果是一样的......
P.S。我在Ubuntu 14.04上有Python 2.7.6
答案 0 :(得分:0)
答案 1 :(得分:0)
请参阅https://docs.djangoproject.com/en/1.9/ref/request-response/#django.http.HttpResponse.content
HTTPResponse.content在文档中标注为字节字符串(https://github.com/django/django/blob/master/django/http/response.py#L225),应编码为DEFAULT_CHARSET
,默认情况下为utf-8
但在我们这两种情况下,这似乎都没有通过测试。
我的解决方案是告诉Python request.content应该具有unicode编码:
def test_students_list(self):
# make request to the server to get homepage page
response = self.client.get(self.url)
# do we have student name on a page?
self.assertIn('Vitaliy', unicode(response.content, encoding='utf-8'))
答案 2 :(得分:0)
改为使用self.assertContains(response, 'Vitaliy')
。