且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

测试用户登录成功

更新时间:2023-08-25 14:14:46


这不是***的答案。请参阅 https://***.com/a/35871564/307511



Chronial 已经给了
一个很好的例子,说明如何使这个断言如下。他的答案比我现在的代码







最直截了当测试用户登录的方法是通过测试Client对象:

  self.assertIn('_ auth_user_id',self。 client.session)

您还可以检查特定用户是否登录:

  self.assertEqual(int(self.client.session ['_ auth_user_id']),user.pk)

作为附加信息, response.request 对象不是一个 HttpRequest object;相反,它是一个普通的dict,有一些关于实际请求的信息,所以它不会有用户属性。



另外,测试 response.context 对象是不安全的,因为你不会有上下文。


How can I test that a user is logged in after submitting the registration form?

I tried the following but it returns True even before I added the login logic to my registration view.

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

The code that's being tested:

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

This is not the best answer. See https://***.com/a/35871564/307511

Chronial has given an excellent example on how to make this assertion below. His answer better than mine for nowadays code.


The most straightforward method to test if a user is logged in is by testing the Client object:

self.assertIn('_auth_user_id', self.client.session)

You could also check if a specific user is logged in:

self.assertEqual(int(self.client.session['_auth_user_id']), user.pk)

As an additional info, the response.request object is not a HttpRequest object; instead, it's an ordinary dict with some info about the actual request, so it won't have the user attribute anyway.

Also, testing the response.context object is not safe because you don't aways have a context.