Advertisement
Guest User

Untitled

a guest
Mar 30th, 2017
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.06 KB | None | 0 0
  1. # author: michal@mazurek-inc.co.uk
  2.  
  3. @pytest.fixture
  4. def mock_file():
  5. """Mock file open."""
  6.  
  7. @contextlib.contextmanager
  8. def contextmanager(file_name: str, content: bytes, obj):
  9. """
  10. Context manager for mocking file.
  11.  
  12. :param file_name: file name to be mocked,
  13. :param content: content in bytes
  14. :param obj: object to be patched where `open` will be called from
  15.  
  16. module_a.py
  17.  
  18. def func():
  19. with open("some.txt") as some_file:
  20. return some_file.decode("utf8")
  21.  
  22. test_module_a.py:
  23. from .fixtures import mock_file
  24. import module_a
  25.  
  26. def test_func(mock_file):
  27.  
  28. with mock_file("some.txt", b"test123", module_a) as mocked_open:
  29. assert mocked_open.called
  30. assert module_a.func() == "test123"
  31.  
  32. """
  33. with mock.patch.object(obj, 'open') as patched_function:
  34. patched_function.return_value.__enter__.return_value = (
  35. io.BytesIO(content))
  36. yield patched_function
  37.  
  38. return contextmanager
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement