Reputation: 173
I have a viewset for services and an action method defined as:
@action(
methods=['patch'], detail=True, url_name='deploy', url_path='deploy')
def deploy(self, request, pk=None):
"""
An extra action for processing requests
"""
# Gets current instance
instance = self.get_object()
[...]
# Sends GET request
get = APIServiceRequestRouter()
item_list = get.get_data_request()
My get_data_request() method will send a get request to a url, which will return a json response. But of course, this goes out to a third-party api, which I want to mock in my unit test.
I have this unit test for my deploy action endpoint on my services viewset, which currently only test the send of a patch payload to the endpoint. So I need to add a mocked get response as well:
def test_valid_deploy(self) -> None:
"""Test an valid deploy"""
mock_request
response = self.client.patch(
reverse('services-deploy', kwargs={'pk': self.service2.pk}),
data=json.dumps(self.deploy_payload),
content_type='application/json'
)
self.assertEqual(response.status_code, status.HTTP_206_PARTIAL_CONTENT)
What I'm not sure is how to add a mocked get response into this unit test. The error I'm getting when I run my unit tests is that in my test_valid_deploy is that the get_data_request() method I have this:
response = http_get_request.delay(api_url)
response_obj = response.get()
item_ids = response_obj['item_id']
But of course response_obj is empty or of NoneType and therefore the ['item_id'] key does not exist, I get a TypeError: 'NoneType' object is not subscriptable
error.
My thoughts then turned to mocking the get to populate response_obj with relevant data so that my test passes.
Any thoughts or help would be very much appreciated.
Upvotes: 0
Views: 1101
Reputation: 1698
Try mocking the return value of get_data_request
instead?
@mock.patch('path.to.APIServiceRequestRouter.get_data_request')
def test_valid_deploy(self, mocked_get_data_request):
mocked_get_data_request.return_value = {"key": "value"} # your mocked object here
# rest of the test...
Upvotes: 1