函数assertIn导致UnicodeDecodeError

时间:2016-03-15 06:42:47

标签: django unit-testing

在测试我的Django 1.9项目期间,我收到一个错误:

enter image description here

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

3 个答案:

答案 0 :(得分:0)

您是否尝试使用以下方法定义Python源代码编码:

# - - 编码:utf-8 - -

正如PEP 0263中的建议。

答案 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')