Author xtreak
Recipients Anvil, cjw296, mariocj89, michael.foord, xtreak
Date 2019-09-05.07:11:42
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1567667502.78.0.416880356104.issue37669@roundup.psfhosted.org>
In-reply-to
Content
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"
History
Date User Action Args
2019-09-05 07:11:42xtreaksetrecipients: + xtreak, cjw296, michael.foord, mariocj89, Anvil
2019-09-05 07:11:42xtreaksetmessageid: <1567667502.78.0.416880356104.issue37669@roundup.psfhosted.org>
2019-09-05 07:11:42xtreaklinkissue37669 messages
2019-09-05 07:11:42xtreakcreate