2013-06-28 42 views
3
  • 我測試形式
  • 可以將用戶登錄,或匿名,當與形式
  • 如果表單提交成功,用戶將被記錄在
  • 如果表單失敗,用戶將保持原樣
  • 我想通過單元測試來確認此行爲。

django.test.Client確實有這樣的事情login方法,但由於一個response對象我如何確定誰登錄?如何在Django單元測試測試AnonymousUser

data = {'email':'[email protected]','password':'abc'} 
    c = Client() 
    # here was can assume `request.user` is the AnonymousUser 
    # or I can use `c.login(..)` to log someone in 
    r = c.post('/myform/', data) 

如果我要提交第二個請求,我的單元測試是否可以確定request.user現在是誰?

回答

6

你可以這樣做:

client = Client() 
# here was can assume `request.user` is the AnonymousUser 
# or I can use `c.login(..)` to log someone in 
from django.contrib import auth 
user = auth.get_user(client) # it returns User or AnonymousUser 

if user.is_anonymous(): 
    ... 

它的工作原理,因爲客戶保存的用戶會話(client.session)。