2

I wrote a custom authentication backend, I used it in my views to prove that it is working, however I would like to test it so in case it breaks in future for whatever reason, I would know. I think the problem may be because I have no request in the test, so no request is passed into the authenticate method. If this is the problem, then how can I pass a valid request into the authenticate method and test it so the test passes. In other words, can someone please show me a test that passes for the authentication backend below

backends.py

class EmailBackend(BaseBackend): def authenticate(self, request, email=None, password=None): try: user = User.objects.filter(email=email).first() if user.check_password(password): return user else: return None except User.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None 

test_backends.py

class TestUserBackend(TestCase): def test_authenticate(self): user = UserFactory() authenticated_user = authenticate(email=user.email, password=user.password) self.assertEqual(authenticated_user, user) 

UserFactory() is from factory boy. I have also checked that user.password is hashed and the same as user.password which is also hashed. But I keep getting None != the user.email that was generated . Thanks for your help.

1 Answer 1

1

try:

 self.c = APIClient() authenticated_user = authenticate(self.c.request, email=user.email, password=user.password) 
Sign up to request clarification or add additional context in comments.

1 Comment

Please don't post only code as an answer, but also provide an explanation of what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.