Test that user was logged in successfully
Solution 1:
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
Solution 2:
This is not the best answer. See https://stackoverflow.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.