I created a custom authentication backend for my DRF application. I can't figure out how to test it. Calling the client.post calls my authenticate function (cause that's in my view) But I need to mock an internal method in my ModelBackend.
Kinda confused how to go about this?
View:
class Web3UserToken(APIView):
authentication_classes = []
permission_classes = []
def post(self, request, **kwargs):
public_address = request.data["public_address"]
web3 = Web3Backend()
user, token = web3.authenticate(request)
if token:
return JsonResponse({'token': token})
else:
return Response({'message': 'Missing token'}, status=400)
Test:
class TestWeb3AuthBackend(APITestCase): def setUp(self): #TODO: set up test user self.client = APIClient() #self.factory = APIRequestFactory()
def test_authenticatepasseswithexistinguser(self):
self.user = Web3User(public_address=TEST_PUBLIC_ADDRESS)
auth_backend = Web3Backend()
import ipdb; ipdb.sset_trace()
request = self.client.post('/api/token/', {'public_address': TEST_PUBLIC_ADDRESS, 'nonce': '0xsomething_random'},follow=True)
with mock.patch.object(auth_backend, '_check_nonce', return_value=True) as method:
token, user = auth_backend.authenticate(request)
self.assertTrue(token)
self.assertTrue(user)