[ACCEPTED]-django - get user logged into test client-testing
The test client is request-agnostic. It 16 doesn't inherently hold information about 15 what users are logged in. (Neither does 14 your actual webserver or the Django dev 13 server, either, for obvious reasons, and 12 those same reasons apply here).
login
is simply 11 a convenience method on the test client 10 to essentially mimic a POST to /login/
with the 9 defined user credentials. Nothing more.
The 8 actual user is available on the request
just like 7 in a view. However, since you don't have 6 direct access to the view, Django makes 5 request
available on the view's response. After 4 you actually use the test client to load 3 a view, you can store the result and then 2 get the user via:
response.request.user
More recent versions of 1 Django will use:
response.wsgi_request.user
Actually you can't access the current user 3 via a test client response.
However, you 2 can check if some user is logged in. Inspecting 1 self.client.session
will do:
self.client.session['_auth_user_id']
>>> 1
There is a more detailed answer for this.
I don't know which version you are using. Since 3 1.10.2, there is a wsgi_request
attribute in response
, it serves 2 as request
object in your view.
So It's very simple 1 to get logged in user:
response.wsgi_request.user
You can log in with a test user like so:
from django.contrib.auth.models import User
user = User.objects.create_user('foo', 'myemail@test.com', 'bar')
self.client.login(username='foo', password='bar')
Now, you can just use user
in 1 your tests:
self.assertEqual(created_model_object.user, user)
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.