django - Django Rest Mocking a Get request
问题描述
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.
解决方案
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...
推荐阅读
- javascript - 电子邮件返回数字值而不是名称
- string - 如何在golang中拆分长结构标签?
- regex - 如何使用正则表达式将文本拆分为块,在特定字符上断开?
- mercurial - 是否可以删除架子中的单个文件?
- java - 使用 DataFlow 从多个 PubSub 主题流式传输到 BigQuery 时消息卡在 GBP 中?
- google-apps-script - 当单元格符合谷歌表格中的标准时发送电子邮件
- javascript - 为什么我不能在不丢失 JS 精度的情况下将字符串转换为数字?
- angular - 从http响应对象Angular 6获取属性的值
- javascript - 在svg unsig javascript中获取最长线段的长度
- python - 升级到 Django 2.1 500 错误消息后不再发送