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 hidden or 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() |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@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.