2016-03-15 67 views
1

在測試過程中爲我的Django 1.9項目中,我得到一個錯誤:功能assertIn導致的UnicodeDecodeError

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

的結果是一樣的...

附:我的Python 2.7.6在Ubuntu 14.04

+0

我有同樣的,這是因爲響應包含unicode但HTTPResponse.content正在給你ascii。我無法弄清楚如何改變這一點。運行代碼的系統在默認語言環境中具有UTF-8,Django的默認設置爲響應爲unicode。我很難過。 – wjdp

回答

0

你有沒有嘗試使用來定義您的Python源代碼編碼:

# - - 編碼:UTF-8 - -

PEP 0263建議。

+0

是的,我做到了!這很有用!謝謝! – alexleon

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')) 
0

使用self.assertContains(response, 'Vitaliy')代替。