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)
Kyle Calica-St
  • 2,629
  • 4
  • 26
  • 56

1 Answers1

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.

ebllg
  • 154
  • 3
  • 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. – Kyle Calica-St Dec 04 '21 at 22:48
  • this worked: https://stackoverflow.com/questions/28421797/django-rest-framework-apirequestfactory-request-object-has-no-attribute-query-p/28429552 – Kyle Calica-St Dec 04 '21 at 22:56