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
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.
#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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With