Python 模拟内置&x27;开放式;在contextlib中使用时的函数
我知道以前有人问过这个问题,但我有一个特殊的问题,这意味着我希望mock_open实际返回一个特定的mock对象 我想测试一个函数:Python 模拟内置&x27;开放式;在contextlib中使用时的函数,python,unit-testing,mocking,Python,Unit Testing,Mocking,我知道以前有人问过这个问题,但我有一个特殊的问题,这意味着我希望mock_open实际返回一个特定的mock对象 我想测试一个函数: def foo(src,dest): with contextlib.nested( open(src,'r'), open(dest,'w')) as (src,dest): d = src.read(1) .... 我的问题是,使用mock_open(),如何让它返回一个特定的s
def foo(src,dest):
with contextlib.nested(
open(src,'r'),
open(dest,'w')) as (src,dest):
d = src.read(1)
....
我的问题是,使用mock_open(),如何让它返回一个特定的src和dest mock,以便对它们进行断言?即使我使用mock\u open(mock=mock\u src),它仍然不会传递我想要的对象,而是传递一个新的对象。你想要的是mocked
open
为这两个调用返回一个不同的mock对象:你可以使用side\u effect
来获得该行为,但你需要一点技巧来创建有效的模拟文件处理程序
m = msrc = mock_open() #That create a handle for the first file
mdst = mock_open() #That create a handle for the second file
m.side_effect=[msrc.return_value,mdst.return_value] # Mix the two handles in one of mock the we will use to patch open
with patch("builtins.open", m):
with open("src",'r') as src , open("dest",'w') as dest:
print(src) #Two different mock file!
print(dest)
我为Python3编写了代码,但对于较旧的python来说,翻译代码应该很简单(我注意到您使用的是嵌套的)
我已经给出了一个非常类似的问题的答案,但这个解决方案要好得多!就记录而言您想要的是mocked
打开
为两个调用返回不同的mock对象:您可以使用副作用
来获得该行为,但您需要一些技巧来创建有效的mocked文件处理程序
m = msrc = mock_open() #That create a handle for the first file
mdst = mock_open() #That create a handle for the second file
m.side_effect=[msrc.return_value,mdst.return_value] # Mix the two handles in one of mock the we will use to patch open
with patch("builtins.open", m):
with open("src",'r') as src , open("dest",'w') as dest:
print(src) #Two different mock file!
print(dest)
我为Python3编写了代码,但对于较旧的python来说,翻译代码应该很简单(我注意到您使用的是嵌套的)
我已经给出了一个非常类似的问题的答案,但这个解决方案要好得多!记录在案