Accessing the request.user object when testing Django

clientdjangorequesttesting

I'm trying to access the request.user object when testing my app using django's client class.

from django.test import TestCase
from django.test.client import Client

class SomeTestCase(TestCase):

    def setUp(self):
        self.client = Client()
        self.client.login( username="foo", password="bar")

    def test_one(self):
        response = self.client.get("/my_profile/")
        self.fail( response.request.user )

This will obviously fail, but it fails because response.request doesn't have a user attribute.

AttributeError: 'dict' object has no attribute 'user'

Is there any way to access the user object from the client instance? I want to do this in order to check if some test user's data is properly rendered. I can try to tackle this by setting up all the necessary info during setUp, but before I do that I wanted to check if I'm not just missing something.

Best Answer

Use response.context['user'].

User is automatically available in the template context if you use RequestContext. See auth data in templates doc.

Otherwise i believe you should just query it:

 def test_one(self):
    response = self.client.get("/my_profile/")
    user = User.objects.get(username="foo")
    self.fail( user.some_field == False )
Related Topic