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 <>
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 == "data1"

        with open("file2") as file2:
            assert == "data2"

            with open("file1") as file3:
                assert == "d"

        assert == ""

    with open("defaultfile") as file4:
        assert == "default mock data"
Date User Action Args
2019-09-05 07:11:42xtreaksetrecipients: + xtreak, cjw296, michael.foord, mariocj89, Anvil
2019-09-05 07:11:42xtreaksetmessageid: <>
2019-09-05 07:11:42xtreaklinkissue37669 messages
2019-09-05 07:11:42xtreakcreate