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 tes
Solution 1:
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 openwith patch("builtins.open", m):
withopen("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
Post a Comment for "Mock Builtin 'open" Function When Used In Contextlib"