How do I setup a unit test user for django app? The unit test can't login

dolphus333 picture dolphus333 · Apr 29, 2016 · Viewed 11.1k times · Source

I've enabled login authentication for my django app. Unit tests for views are not working because they get stuck at the login page. Setting a breakpoint immediately after the view's response is returned and using

print response.content

results in output that contains the phrase 'please login'

How do I setup a user so the testcase can login? I've tried using my username and password, but it doesn't work in the unit test context.

Answer

dolphus333 picture dolphus333 · Apr 29, 2016

The following code inserted at the beginning of the testcase creates a user, logs them in, and allows the rest of the test to contiue

self.user = User.objects.create_user(username='testuser', password='12345')
login = self.client.login(username='testuser', password='12345')