【发布时间】:2013-04-10 18:37:47
【问题描述】:
所以,我刚刚开始在 Django 项目中使用 mock。我正在尝试模拟视图的一部分,该视图向远程 API 发出请求以确认订阅请求是真实的(根据我正在努力的规范的一种验证形式)。
我所拥有的类似于:
class SubscriptionView(View):
def post(self, request, **kwargs):
remote_url = request.POST.get('remote_url')
if remote_url:
response = requests.get(remote_url, params={'verify': 'hello'})
if response.status_code != 200:
return HttpResponse('Verification of request failed')
我现在想做的是使用 mock 来模拟 requests.get 调用以更改响应,但我不知道如何为补丁装饰器执行此操作。我以为你会这样做:
@patch(requests.get)
def test_response_verify(self):
# make a call to the view using self.app.post (WebTest),
# requests.get makes a suitable fake response from the mock object
我如何做到这一点?
【问题讨论】:
-
死机使用模拟?还有 django.test.client.RequestFactory - docs.djangoproject.com/en/1.5/topics/testing/advanced/…
-
只是为了将来的观众,提问者想模拟一个外部 API 调用。不是对视图本身的调用。在这种情况下,模拟似乎非常明智。
-
根据@aychedee,这确实是我提出这个问题的目标。
标签: python django unit-testing mocking django-testing