Skip to content

Instantly share code, notes, and snippets.

@MichalMazurek
Created March 30, 2017 12:25
Show Gist options
  • Save MichalMazurek/e5df48ae578ab03f98ff101780634fa3 to your computer and use it in GitHub Desktop.
Save MichalMazurek/e5df48ae578ab03f98ff101780634fa3 to your computer and use it in GitHub Desktop.
Pytest fixture for mocking file open
# author: michal@mazurek-inc.co.uk
@pytest.fixture
def mock_file():
"""Mock file open."""
@contextlib.contextmanager
def contextmanager(file_name: str, content: bytes, obj):
"""
Context manager for mocking file.
:param file_name: file name to be mocked,
:param content: content in bytes
:param obj: object to be patched where `open` will be called from
module_a.py
def func():
with open("some.txt") as some_file:
return some_file.decode("utf8")
test_module_a.py:
from .fixtures import mock_file
import module_a
def test_func(mock_file):
with mock_file("some.txt", b"test123", module_a) as mocked_open:
assert mocked_open.called
assert module_a.func() == "test123"
"""
with mock.patch.object(obj, 'open') as patched_function:
patched_function.return_value.__enter__.return_value = (
io.BytesIO(content))
yield patched_function
return contextmanager
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment