无法模拟第三方 api 调用
Can't mock a third party api call
我有一个执行第三方 API 调用的视图:
from .atoca_api_calls import atoca_api_call
def atoca_api_call_view(request):
# some code
data = atoca_api_call(**params) # the actual API call happens in this func
# some code
我的意图是只模拟 atoca_api_call()
函数而不是整个视图。
class AtocaTestCase(TestCase):
def setUp(self):
# some code
@patch('crm.atoca_api_calls.atoca_api_call')
def test_atoca_call(self, mock_atoca_api_call):
mock_atoca_api_call.return_value = MagicMock(
status_code=200,
response=some_json # just returns some json
)
url = reverse('crm:atoca-api-call') # url related to `atoca_api_call_view`
response = self.client.post(url, some_others_params)
# various asserts
测试工作正常,但 atoca_api_call()
未被模拟。
我知道 where to patch:
@patch('crm.views.atoca_api_call', autospec=True)
提出 ValueError
:
ValueError: Failed to insert expression "<MagicMock name='mock.__getitem__().__getitem__().__getitem__()().resolve_expression()' id='140048216397424'>" on crm.Company.atoca_id. F() expressions can only be used to update, not to insert.
这可能是一个简单的问题,我没有经验,非常感谢任何帮助。
我看到 atoca_api_call()
它被嘲笑了。问题是 return 值。
mock_atoca_api_call.return_value = MagicMock(
status_code=200,
response=some_json # just returns some json
)
我假设 JsonResponse
或 Response(data)
不确定您在做什么 return,这应该是一个正确的回应。尝试:
mock_atoca_api_call.return_value = JsonResponse(
some_json # just returns some json
)
我有一个执行第三方 API 调用的视图:
from .atoca_api_calls import atoca_api_call
def atoca_api_call_view(request):
# some code
data = atoca_api_call(**params) # the actual API call happens in this func
# some code
我的意图是只模拟 atoca_api_call()
函数而不是整个视图。
class AtocaTestCase(TestCase):
def setUp(self):
# some code
@patch('crm.atoca_api_calls.atoca_api_call')
def test_atoca_call(self, mock_atoca_api_call):
mock_atoca_api_call.return_value = MagicMock(
status_code=200,
response=some_json # just returns some json
)
url = reverse('crm:atoca-api-call') # url related to `atoca_api_call_view`
response = self.client.post(url, some_others_params)
# various asserts
测试工作正常,但 atoca_api_call()
未被模拟。
我知道 where to patch:
@patch('crm.views.atoca_api_call', autospec=True)
提出 ValueError
:
ValueError: Failed to insert expression "<MagicMock name='mock.__getitem__().__getitem__().__getitem__()().resolve_expression()' id='140048216397424'>" on crm.Company.atoca_id. F() expressions can only be used to update, not to insert.
这可能是一个简单的问题,我没有经验,非常感谢任何帮助。
我看到 atoca_api_call()
它被嘲笑了。问题是 return 值。
mock_atoca_api_call.return_value = MagicMock(
status_code=200,
response=some_json # just returns some json
)
我假设 JsonResponse
或 Response(data)
不确定您在做什么 return,这应该是一个正确的回应。尝试:
mock_atoca_api_call.return_value = JsonResponse(
some_json # just returns some json
)