How to test custom authentication backend in django

990 views Asked by At

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

There are 1 answers

1
Akuseru On

try:

 self.c = APIClient()
 authenticated_user = authenticate(self.c.request, email=user.email, password=user.password)