classification
Title: Add a recipe in unittest.mock examples about mock_open per file
Type: behavior Stage: patch review
Components: Documentation Versions: Python 3.9, Python 3.8, Python 3.7
process
Status: open Resolution:
Dependencies: Superseder:
Assigned To: docs@python Nosy List: cjw296, docs@python, lisroach, mariocj89, michael.foord, xtreak
Priority: normal Keywords: patch

Created on 2019-09-13 10:54 by xtreak, last changed 2019-09-13 11:44 by xtreak.

Pull Requests
URL Status Linked Edit
PR 16090 open xtreak, 2019-09-13 11:44
Messages (1)
msg352285 - (view) Author: Karthikeyan Singaravelan (xtreak) * (Python triager) Date: 2019-09-13 10:54
With issue37669 it was proposed to refactor out the mock_open handler to return different mocks per file and an API change to make sure read_data accepts a dictionary of file and return values it can only land on master if accepter. It's already possible now with using side_effect to return per file content. Adding it would be a good example like below so that users can know this usage. I can prepare a PR for this.


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-13 11:44:22xtreaksetkeywords: + patch
stage: patch review
pull_requests: + pull_request15711
2019-09-13 10:54:43xtreakcreate