I have an external API POST call that is being made from within my views.py as such:
class MyView(APIView):
def post(self, request):
my_headers = {
"Content-Type": "application/json"
}
response = requests.post("https://some-external-api.com", data=json.dumps(request.data), headers=my_headers)
return Response(status.response.status_code)
As you can see, it is a very simple case of making a POST call to the external API with the same data that is received to the views endpoint.
Right now, I am trying to create a unit test for this, while mocking the response from "https://some-external-api.com" so I obviously don't have to make an actual call to it every time this unit test runs. But I am having difficulty as I can't get the mock aspect to work, and everytime the request is sent to the actual external endpoint.
I know there are a lot of examples online, but nothing that I've tried seems to work. I've not seen examples whereby the mocked response should come from the view file itself. As of now, I have this:
@patch('requests.post')
def test_external_api_call(self, mock_post)
mock_post.return_value.ok = True
response = self.client.post(reverse('my-view'), {
//my random dummy json object goes here
}, format='json')
self.assertEqual(response.status_code, 200)
As I mentioned, with the above code, there is an actual call being made to "https://some-external-api.com" rather than it being mocked.