Kyle Calica-St
Kyle Calica-St

Reputation: 2963

Testing a custom auth backend with Django RestFramework

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)

Upvotes: 1

Views: 1162

Answers (1)

ebllg
ebllg

Reputation: 154

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.

Upvotes: 3

Related Questions