Created
August 11, 2012 10:03
-
-
Save JensRantil/3323323 to your computer and use it in GitHub Desktop.
How to check if all files were closed using Mock
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
@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
Interesting idea, I gave it a go with current version of flexmock. Ideally it could be much more elegant and short, but as flexmock doesn't have a built-in way to proxy for a builtin object it's arguably even more cumbersome than the Mock version. It avoids the need to globally track open files and doing the manual verification at the end, but the initial setup feels brittle and isn't very intuitive. I'll consider adding this use-case though, so could turn into one-liner using flexmock in the future..