django.test.Client
确实有login
方法用于此类操作,但如果有response
个对象,如何确定谁登录?
data = {'email':'john@example.com','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)
如果我要提交第二个请求,我的unittest可以确定request.user
现在是谁吗?
答案 0 :(得分: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 保持用户会话(client.session)。