Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 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
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement