模拟python http请求测试和开发

时间:2017-11-30 16:14:19

标签: python unit-testing testing mocking

我正在使用python“requests”并且效果很好,但现在我希望能够“模拟”响应而不是触及真实的服务器。

我这样做:

r = requests.get(self.url+'/somepath', params=payload)

在guzzlephp我可以这样做:

$mock = new MockHandler([
    new Response(200, ['X-Foo' => 'Bar'], 'mocked response')
]);

$handler = HandlerStack::create($mock);

$client = new Client(['handler' => $handler]);

在请求或python中有类似的东西吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

您可以使用此库 https://requests-mock.readthedocs.io/en/latest/index.html并执行类似

的操作
>>> import requests
>>> import requests_mock

>>> with requests_mock.Mocker() as m:
...     m.get(self.url+'/somepath', text='mocked response')
...     requests.get(self.url+'/somepath').text
...
'mocked response'