Karthikeyan Singaravelan <[email protected]> added the comment:
Using a side_effect is one way to achieve this currently if I understand the
use case correctly. For every open side_effect will be called and hence it will
return a new mock_open with read_data for the given filename used inside the
context. This can handle nested calls since each will have it's own mock_open
object. PR seems to do similar approach to refactor out to created predefined
mock_open per filename and to return objects from a dictionary.
from unittest.mock import mock_open, patch
DEFAULT_MOCK_DATA = "default mock data"
data_dict = {"file1": "data1",
"file2": "data2"}
def open_side_effect(name):
return mock_open(read_data=data_dict.get(name, DEFAULT_MOCK_DATA))()
with patch(f"{__name__}.open", side_effect=open_side_effect):
with open("file1") as file1:
assert file1.read() == "data1"
with open("file2") as file2:
assert file2.read() == "data2"
with open("file1") as file3:
assert file3.read(1) == "d"
assert file1.read() == ""
with open("defaultfile") as file4:
assert file4.read() == "default mock data"
----------
_______________________________________
Python tracker <[email protected]>
<https://bugs.python.org/issue37669>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com