我该如何模拟request.Session.send()方法?

时间:2019-04-19 08:07:06

标签: python mocking python-requests

我该如何嘲笑它?我已经上课了

from requests import Session
class MySession(Session):
    def __init__(self, *args, **kwargs):
        super(MySession).__init__(*args, **kwargs)
    ...
    def do_query(self, *args, **kwargs):
    ...
    # some preparation
        req = Request(
            method=method.upper(),
            url=url,
            headers=headers,
            files=files,
            data=data,
            json=json,
            params=params,
            auth=auth,
            cookies=None,
            hooks=None,
        )

        prepared = self.prepare_request(req)

        settings = self.merge_environment_settings(
            prepared.url, {}, stream, check_ssl, None
        )

        send_kwargs = {
            'timeout': timeout,
            'allow_redirects': True,
        }

        send_kwargs.update(settings)
        resp = self.send(prep, **send_kwargs)

在测试中,我想模拟send方法并使用自己的结果。

class FakeResult(object):
    def __init__(self):
        self.status_code = 200
        self.url = 'http://127.0.0.1/test_url'
        self.content = 'content'

class TestFilter(unittest.TestCase):
    @mock.patch('requests.Session.send')
    def test_test(self, session_mock):
        session_mock.return_value = FakeResult()
        req = CatchData('test')
        s = MySession()

        # Here the problem
        s.do_query(req)    

在do_query内部,方法self.send()尝试发送数据。我不想要这个。怎么嘲笑呢? do_query的许多部分是request.Request的一部分。

0 个答案:

没有答案