Search code examples
pythondjangotestingdjango-testingdjango-tests

Django: How to associate a user with a request factory


I am writing some tests for a form on a Django site. I want to test that a logged in user is able to use the form assuming correct input. To that end, I am using a Django request factory. I can't seem to get my test user logged in though. That, or I'm not even making the request correctly. I'm not sure. Relevant code below:

def create_user():
        username = 'User '+id_generator()
        return User.objects.create(username = username, password = 'password')

def test_can_register_deck(self):
        t = create_empty_tourney()
        u = create_user()
        d = create_deck(u)
        rf = RequestFactory()
        request = rf.post(reverse('tourney:tourney', args=(t.slug,)),{'deck' : d})
        request.user = u
        response = self.client.get(reverse('tourney:tourney', args=(t.slug,)), request)
        self.assertEqual(response.status_code, 200)

The request has to think the user is logged in, or the rest of the test won't work. This throws no errors, but I'm not even sure my response is utilizing the request correctly. Am I correctly telling the test to "make a post request to the tourney page as this user, and try to submit a deck"?


Solution

  • I think that the RequestFactory and the client are two different ways of testing django views.

    The request that is returned from rf.post is meant to be passed directly to a view function. If you were to do that, i think you will find that, the user will be detected as logged in.

    I looked at the source, and the documentation, and I don't see where the test client accepts a request. You can log in a user with the test client using:

    self.client.login(
       username=u.username,
       password='password')