Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test that user was logged in successfully

Tags:

django

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 
like image 776
Pickels Avatar asked Apr 14 '11 09:04

Pickels


People also ask

How do you check if a user is logged in Python?

To check if a user is logged in with Python Django, we can use the request. user. is_authenticated property in our view. to check if the current user is authenticated with request.

How do you test the login feature of a Web application?

#1) Verify if a user can log in with a valid username and password. #2) Verify if a user cannot log in with an invalid username or password. Check permutation and combinations of this. #3) Verify the 'Keep me Sign In' option.


1 Answers

You can use the get_user method of the auth module. It says it wants a request as parameter, but it only ever uses the session attribute of the request. And it just so happens that our Client has that attribute.

from django.contrib import auth user = auth.get_user(self.client) assert user.is_authenticated 
like image 60
Chronial Avatar answered Sep 18 '22 09:09

Chronial