Django test Client simulate logged in user

时间:2015-09-01 22:16:26

标签: django django-testing

I am new to Django test Client. I want to test a view that uses @login_required . I was wondering if I can do that using the simple Client() like this:

>>> from django.test import Client
>>> c = Client()
>>> r = c.get("/libros/nuevo_libro/perfil/farseer/")

But, of course, the response is always a 302:

>>> r.status_code
302

Cause the @login_required decorator redirects it to the login page.

Is it possible to simulate in this kind of tests that the user is logged in?

1 个答案:

答案 0 :(得分:3)

The test client has a login method.

c = Client()
c.login(username='fred', password='secret')
response = c.get("/libros/nuevo_libro/perfil/farseer/")