use*_*876 1 python unit-testing mocking
我知道之前有人问过这个问题,但我有一个特殊的问题,这意味着我希望 mock_open 实际返回一个特定的模拟对象。
我有一个要测试的功能:
def foo(src,dest):
with contextlib.nested(
open(src,'r'),
open(dest,'w')) as (src,dest):
d = src.read(1)
....
Run Code Online (Sandbox Code Playgroud)
我的问题是,使用 mock_open(),如何让它返回特定的 src 和 dest 模拟,以便我可以对它们进行断言?即使我使用 mock_open(mock=mock_src) 它仍然没有传递我想要的对象,而是一个新的对象。
你想要的是open模拟为这两个调用返回一个不同的模拟对象:你可以side_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)
Run Code Online (Sandbox Code Playgroud)
我为 python 3 编写了代码,但对于较旧的 python 应该很简单(我注意到你使用了嵌套)。
我已经对一个非常相似的问题给出了答案,但该解决方案要好得多!仅用于记录Python 模拟内置在使用两个不同文件的类中“打开”