如何在提交注册表单后测试用户是否已登录?
我尝试了以下操作但是True在我将登录逻辑添加到注册视图之前它就会返回.
def test_that_user_gets_logged_in(self):
response = self.client.post(reverse('auth-registration'),
{ 'username':'foo',
'password1':'bar',
'password2':'bar' } )
user = User.objects.get(username='foo')
assert user.is_authenticated()
Run Code Online (Sandbox Code Playgroud)
正在测试的代码:
class RegistrationView(CreateView):
template_name = 'auth/registration.html'
form_class = UserCreationForm
success_url = '/'
def auth_login(self, request, username, password):
'''
Authenticate always needs to be called before login because it
adds which backend did the authentication which is required by login.
'''
user = authenticate(username=username, password=password)
login(request, user)
def form_valid(self, form):
'''
Overwrite form_valid to login.
'''
#save the user
response = super(RegistrationView, self).form_valid(form)
#Get the user creditials
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
#authenticate and login
self.auth_login(self.request, username, password)
return response
Run Code Online (Sandbox Code Playgroud)
emy*_*ler 70
这不是最好的答案.请参阅/sf/answers/2511009511/
Chronial给出了一个很好的例子,说明如何在下面做出这个断言.对于现在的代码,他的答案比我的好.
测试用户是否登录的最简单方法是测试Client对象:
self.assertIn('_auth_user_id', self.client.session)
Run Code Online (Sandbox Code Playgroud)
您还可以检查特定用户是否已登录:
self.assertEqual(int(self.client.session['_auth_user_id']), user.pk)
Run Code Online (Sandbox Code Playgroud)
作为附加信息,response.request对象不是HttpRequest对象; 相反,它是一个普通的dict,其中包含有关实际请求的一些信息,因此它user无论如何都不具备该属性.
此外,测试response.context对象是不安全的,因为你没有远离上下文.
Chr*_*ial 63
您可以使用模块的get_user方法auth.它说它想要一个请求作为参数,但它只使用session请求的属性.只是碰巧我们Client有这个属性.
from django.contrib import auth
user = auth.get_user(self.client)
assert user.is_authenticated()
Run Code Online (Sandbox Code Playgroud)
模型is_authenticated()上的方法User总是返回True.False则返回request.user.is_authenticated()在该情况下request.user是一个实例AnonymousUser,其is_authenticated()方法总是返回False.在测试时你可以看看response.context['request'].user.is_authenticated().
您还可以尝试访问需要登录的测试中的另一个页面,并查看是否response.status返回200或302(重定向login_required).
| 归档时间: |
|
| 查看次数: |
23065 次 |
| 最近记录: |