Skip to content

Instantly share code, notes, and snippets.

@JensRantil
Created August 11, 2012 10:03
Show Gist options
  • Save JensRantil/3323323 to your computer and use it in GitHub Desktop.
Save JensRantil/3323323 to your computer and use it in GitHub Desktop.
How to check if all files were closed using Mock
import mock
files_opened = []
real_open = open # Needed since I will wrap open
def open_wrapper(*args, **kw):
opened_file = mock.MagicMock(wraps=real_open(*args, **kw))
files_opened.append(opened_file)
return opened_file
open_mock = mock.MagicMock(side_effect=open_wrapper)
open_mock.__enter__.side_effect = open_wrapper
with mock.patch('__builtin__.open', open_mock, create=True):
import myapplication
myapplication.run()
for opened_file in files_opened:
opened_file.close.assert_called_once_with()
@JensRantil
Copy link
Author

@has207 Always fun to see it in another implementation. Seems like this is (currently) one of those things that are still a little clumsy. The things is, it's a highly useful test to catch all those file not closed. I am surprised this problem has surfaces before.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment