2010-05-20 66 views
4

我正在使用django.test.client.Client來測試當用戶登錄時是否顯示一些文本。但是,我的客戶端對象不會' t似乎讓我登錄。爲什麼django.test.client.Client不讓我登錄

該測試通過,如果手動完成與Firefox,但不完成與客戶端對象。

class Test(TestCase): 
    def test_view(self): 
     user.set_password(password) 
     user.save() 

     client = self.client 
     # I thought a more manual way would work, but no luck 
     # client.post('/login', {'username':user.username, 'password':password}) 
     login_successful = client.login(username=user.username, password=password) 
     # this assert passes 
     self.assertTrue(login_successful) 

     response = client.get("/path", follow=True) 
     #whether follow=True or not doesn't seem to work 

     self.assertContains(response, "needle") 

當我打印響應它返回被隱藏的登錄表單:

{% if not request.user.is_authenticated %} 
    ... form ... 
{% endif %} 

當我運行ipython manage.py shell這證實。

問題似乎是客戶端對象沒有保持會話認證。

+0

看着這個我不確定問題在哪裏。你能明確表明客戶端正在註銷嗎?如果客戶端已經登錄,那麼'client.session!= {}'您可以使用它來顯示客戶端在何處登出。 – tdedecko 2010-05-21 04:13:42

+0

這肯定沒有幫助你,對不起,但我從今天起就有同樣的問題。我不知道改變了什麼。 – Fred 2010-05-21 12:47:13

回答

0

FWIW,Django 1.2的更新(我以前運行1.1.1)修復它。我不知道那裏發生了什麼,考慮到我大約兩個星期前上次運行該測試套件時,它運行得很好。

+0

所以你遇到了同樣的問題? – Mystic 2010-05-21 14:03:46

+0

我也升級到了Django 1.2,問題就消失了。謝謝! – Mystic 2010-05-21 16:46:08

0

我使用RequestContext將登錄用戶置入模板上下文中。

from django.shortcuts import render_to_response 
from django.contrib.auth.decorators import login_required 
from django.template import RequestContext 

@login_required 
def index(request): 
    return render_to_response('page.html', 
          {}, 
          context_instance=RequestContext(request)) 

,並在模板

{% if user.is_authenticated %} ... {{ user.username }} .. {% endif %} 

可正常工作(我不明白這個頁面無需登錄,當我到達那裏時,用戶名中response.content存在)驅動時通過測試客戶端。

+0

我不認爲這是問題。如果我沒有正確導入上下文,那麼它不適用於Firefox以及客戶端。問題是它在Firefox中工作,但與客戶端無關,所以我無法測試功能。 – Mystic 2010-05-21 12:41:24

+0

您使用request.user.is_authenticated(而不是user.is_authenticated)表示您沒有使用上下文。如果它不能通過瀏覽器爲你工作,我會懷疑你沒有將'{'request':request}'傳遞給你的模板。 – 2010-05-21 14:21:58

1

剛發生在我重新測試一直在工作並被遺忘了幾個月的應用程序時。

解決方案(除了更新到Django 1.2之外)是Patch #11821。簡而言之,Python 2.6.5在Cookie模塊中有一些錯誤修正,觸發了測試客戶機中的邊緣案例錯誤。

+0

很好找!這正是我的問題。 – user27478 2010-11-12 20:57:15