本文介紹了如何模擬在 with 語句中使用的 open (使用 Python 中的 Mock 框架)?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
如何使用 unittest.mock代碼>:
def testme(filepath):
with open(filepath) as f:
return f.read()
推薦答案
mock 0.7.0 改變了這樣做的方式,最終支持模擬 python 協(xié)議方法(魔術(shù)方法),特別是使用 MagicMock:
The way to do this has changed in mock 0.7.0 which finally supports mocking the python protocol methods (magic methods), particularly using the MagicMock:
http://www.voidspace.org.uk/python/mock/magicmock.html一個>
作為上下文管理器模擬打開的示例(來自模擬文檔中的示例頁面):
An example of mocking open as a context manager (from the examples page in the mock documentation):
>>> open_name = '%s.open' % __name__
>>> with patch(open_name, create=True) as mock_open:
... mock_open.return_value = MagicMock(spec=file)
...
... with open('/some/path', 'w') as f:
... f.write('something')
...
<mock.Mock object at 0x...>
>>> file_handle = mock_open.return_value.__enter__.return_value
>>> file_handle.write.assert_called_with('something')
這篇關(guān)于如何模擬在 with 語句中使用的 open (使用 Python 中的 Mock 框架)?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!