Python 3 urlopen 上下文管理器模拟 [英] Python 3 urlopen context manager mocking
本文介绍了Python 3 urlopen 上下文管理器模拟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是测试新手,需要一些帮助.
I am new to testing and need some help here.
假设有这个方法:
from urllib.request import urlopen
def get_posts():
with urlopen('some url here') as data:
return json.loads(data.read().decode('utf-8'))
问题是如何测试这个方法(如果可能,使用 mock.patch 装饰器)?
The question is how to test this method (using mock.patch decorator if possible)?
我现在拥有的:
@mock.patch('mymodule.urlopen')
def test_get_post(self, mocked_urlopen):
mocked_urlopen.__enter__ = Mock(return_value=self.test_data)
mocked_urlopen.__exit__ = Mock(return_value=False)
...
但它似乎不起作用.
附言有没有什么方便的方法可以在测试中使用数据变量(哪种类型是 HTTPResponse),以便它可以只是简单的字符串?
P.S. Is there any convenient way to work with data variable (which type is HTTPResponse) in test so it could just be simple string?
推荐答案
好的,我写了一个简单的类来模拟上下文管理器.
Ok, so I have written simple class to simulate context manager.
class PatchContextManager:
def __init__(self, method, enter_return, exit_return=False):
self._patched = patch(method)
self._enter_return = enter_return
self._exit_return = exit_return
def __enter__(self):
res = self._patched.__enter__()
res.context = MagicMock()
res.context.__enter__.return_value = self._enter_return
res.context.__exit__.return_value = self._exit_return
res.return_value = res.context
return res
def __exit__(self, type, value, tb):
return self._patched.__exit__()
用法:
with PatchContextManager('mymodule.method', 'return_string') as mocked:
a = mymodule.method(47) # a == 'return_string'
mocked.assert_called_with(47)
...
这篇关于Python 3 urlopen 上下文管理器模拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文