Quantcast
Viewing all articles
Browse latest Browse all 22

Simple mocking of open as a context manager

Using open as a context manager is a great way to ensure your file handles are closed properly and is becoming common: with open('/some/path', 'w') as f: f.write('something') The issue is that even if you mock out the call to open it is the returned object that is used as a context manager (and has __enter__ and __exit__ called). Using MagicMock from the mock library, we can mock out context managers very simply. ... [320 words]

Viewing all articles
Browse latest Browse all 22

Trending Articles