Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django - get user logged into test client

Tags:

django

testing

In a written django test, how can I get the current logged in user?

For example this is the test I want to write:

def test_author_set_once(self):
    self.client.login(username='Adam', password='password')
    #create an object and test the author is adam
    self.client.login(username='Barry', password='password')
    #modify the first object and test that the author has not changed

So I want to be able to say something like...

self.assertEqual(object.author, self.client.user)

(but I can't)

The way I've coded it at the moment is like this:

self.client.login(username='Adam', password='password')
self.user = User.objects.get(username='Adam')
#create an object 
self.assertEqual(object.author, self.user)

This relies on the assumption that the request.user is the same as a particular user object. I guess it's OK but it seems a bit clunky.

Is there anyway to avoid the assumption?

like image 992
powlo Avatar asked Feb 17 '12 17:02

powlo


2 Answers

The test client is request-agnostic. It doesn't inherently hold information about what users are logged in. (Neither does your actual webserver or the Django dev server, either, for obvious reasons, and those same reasons apply here).

login is simply a convenience method on the test client to essentially mimic a POST to /login/ with the defined user credentials. Nothing more.

The actual user is available on the request just like in a view. However, since you don't have direct access to the view, Django makes request available on the view's response. After you actually use the test client to load a view, you can store the result and then get the user via:

response.request.user

More recent versions of Django will use:

response.wsgi_request.user
like image 143
Chris Pratt Avatar answered Oct 19 '22 01:10

Chris Pratt


Actually you can't access the current user via a test client response.

However, you can check if some user is logged in. Inspecting self.client.session will do:

self.client.session['_auth_user_id']
>>> 1

There is a more detailed answer for this.

like image 40
hso Avatar answered Oct 19 '22 00:10

hso