Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: testing with login_required

Tags:

django

I am trying to test a post request on a view which has login_required.

if i run this in the shell django:

Client().post('/recipes/', {'name' : 'Matar Cauliflower ', 'mass_unit' : '', 'mass_quantity' : '', 'volume_unit' : '1', 'volume_quantity' : '50', 'pieces_unit' : '', 'pieces_quantity' : ''},follow=True).status_code

I get:

<HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/login/?next=/recipes/">

How to pass the login credentials are tell that a user is logged in.

like image 341
Santhosh Avatar asked Apr 29 '18 08:04

Santhosh


1 Answers

For use in unit testing, you can create a test user (which will be deleted after manage.py test finishes running), and provide its credentials to the test client's login() method.

Or you can call that login() method with valid credentials for a user you know exists. You could also use the force_login() method further down that documentation page, but for testing the best practice is to have your tests create a test-only user and log in as that user.

like image 161
James Bennett Avatar answered Oct 04 '22 16:10

James Bennett