import uuid from django.http import HttpRequest from django.test import TestCase from ..authentication import PasswordlessAuthenticationBackend from ..models import Token, User class AuthenticateTest(TestCase): def test_returns_None_if_token_is_invalid_uuid(self): result = PasswordlessAuthenticationBackend().authenticate( HttpRequest(), "no-such-token" ) self.assertIsNone(result) def test_returns_None_if_token_uuid_not_found(self): uid = uuid.uuid4() result = PasswordlessAuthenticationBackend().authenticate( HttpRequest(), uid ) self.assertIsNone(result) def test_returns_new_user_with_correct_email_if_token_exists(self): email = "discoman@example.com" token = Token.objects.create(email=email) user = PasswordlessAuthenticationBackend().authenticate( HttpRequest(), token.uid ) new_user = User.objects.get(email=email) self.assertEqual(user, new_user) def test_returns_existing_user_with_correct_email_if_token_exists(self): email = "discoman@example.com" existing_user = User.objects.create(email=email) token = Token.objects.create(email=email) user = PasswordlessAuthenticationBackend().authenticate( HttpRequest(), token.uid ) self.assertEqual(user, existing_user) def test_can_retrieve_token_by_uuid(self): token = Token.objects.create(email="a@b.cde") fetched = Token.objects.get(pk=token.uid) self.assertEqual(fetched, token)