模拟urllib.request.urlopen的读取函数返回MagicMock签名

时间:2018-01-05 12:20:03

标签: python unit-testing

我试图在Python 3上模拟urllib.request.urlopen的Read方法:

功能代码:

try:
    with request.urlopen(_webhook_url, json.dumps(_message).encode('utf-8')) as _response:
        _response_body = _response.read()
        return _response_body

测试代码:

with mock.patch('urllib.request.urlopen') as mock_urlopen:
    response_mock = MagicMock()
    response_mock.read.return_value = 'ok'
    mock_urlopen.return_value = response_mock


    with self.stubber:
        _response = NotifySlack.lambda_handler(_event)

        self.assertEqual('ok', _response)

如果我致电response_mock.read(),我会得到“好的”#39;返回值,但是当我断言返回值时,我得到一个模拟签名:

Expected :ok
Actual   :<MagicMock name='urlopen().__enter__().read()' id='2148156925992'>

关于模拟为什么不返回分配给read()的值的任何想法?

1 个答案:

答案 0 :(得分:2)

要关注@ jonrsharpe的评论和Python: Mocking a context manager主题,要正确模拟上下文管理器,在这种情况下,您需要这个有趣的外观:

mock_urlopen.return_value.__enter__.return_value.read.return_value = 'ok'
#^^^^^^context manager to return response^^^^^^^|^^^read method^^^