模拟内置“打开"在 contextlib 中使用时的函数 [英] Mock builtin 'open" function when used in contextlib

查看:21
本文介绍了模拟内置“打开"在 contextlib 中使用时的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道以前有人问过这个问题,但我有一个特殊的问题,这意味着我希望 mock_open 实际上返回一个特定的模拟对象.

I know this question has been asked before, but I have a particular problem, meaning I want the mock_open to actually return a specific mock object.

我有一个要测试的功能:

I have a function I want to test:

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_open(mock=mock_src) 它仍然没有传递我想要的对象,而是一个新的对象.

My question is, using mock_open(), how do I get it to return a specific src and dest mock, so I can make assertions on them? Even if I use mock_open(mock=mock_src) it still does not pass the object I want, but a new one.

推荐答案

你想要的是模拟的 open 为两次调用返回不同的模拟对象:你可以使用 side_effect 以获得该行为,但您需要一些技巧来创建有效的模拟文件处理程序

What do you want is that mocked open return a different mock object for the two calls: you can use side_effect to obtain that behavior but you need a little trick to create valid mocked file handler

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)

我为 python 3 编写了代码,但对于较旧的 python 应该很简单地翻译它(我注意到你使用了嵌套).

I wrote the code for python 3 but should be simple translate it for older python (I noted that you use nested).

我已经回答了一个非常相似的问题,但那个解决方案要好得多!仅供记录 Python 模拟使用两个不同的文件在类中内置打开"

I already give an answer to a very similar issue but that solution is much better! Just for the record Python mock builtin 'open' in a class using two different files

这篇关于模拟内置“打开"在 contextlib 中使用时的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆