我是新手測試,需要一些幫助。Python 3 urlopen上下文管理器嘲諷
假定具有這種方法:
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裝飾如果可能的話)?
我現在擁有的一切:
@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)
...
但它似乎並不奏效。
P.S.有什麼方便的方式來處理數據變量(哪種類型是HTTPResponse)在測試中,所以它可能只是簡單的字符串?
我不熟悉'mock'庫,但也許你可以檢查[unittest.mock](https://docs.python.org/3/library/unittest。 mock.html)文件的更多細節。 – Eric
'self.test_data'必須是具有read()方法的對象,而不是字符串。 – jfs