1

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)

1 Answer 1

3

I suggest using RequestFactory for creating a request and passing it to authenticate method, instead of sending a request via Django's test client. This is a unit test and its aim is to test authenticate method of Web3Backend. You don't need to test this functionality through an api call.

Sign up to request clarification or add additional context in comments.

2 Comments

I'll be honest I didn't realize it was actually sending a request, I thought it was creating one. I tried RequestFactory but it returns a WSGIRequest which doesn't have a request.data attribute which I use in my authenticate method. I tried APIRequestFactory as well and it didn't line up with a data object in the request.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.