user1550876
user1550876

Reputation: 109

Mock builtin 'open" function when used in contextlib

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)
         ....

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.

Upvotes: 1

Views: 2609

Answers (1)

Michele d'Amico
Michele d'Amico

Reputation: 23711

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)

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

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

Upvotes: 8

Related Questions