29

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.

1 Answer 1

46

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')
3
  • @rurp you're exactly right. I changed the answer to reflect your comment. Thanks for removing another line from my code!
    – dolphus333
    Apr 30, 2016 at 12:05
  • What if a user with that username exists in the DB? What would happen in tests?
    – theTypan
    Jun 11, 2019 at 13:43
  • The documentation suggests, and my tests used a separate DB for testing so this didn't come up. I'd assume you'd get an error back from create_user.
    – dolphus333
    Jun 16, 2019 at 13:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.