diff options
author | Miss Islington (bot) <31488909+miss-islington@users.noreply.github.com> | 2023-09-08 13:21:51 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-09-08 13:21:51 (GMT) |
commit | 736c413977730fa590a759d2eca3d2ac611fd5ec (patch) | |
tree | 50a82706c806c6824588bd5f6cc40098e985242d /Doc/library | |
parent | 29404b6d255b41989b0e490539781db824b368b1 (diff) | |
download | cpython-736c413977730fa590a759d2eca3d2ac611fd5ec.zip cpython-736c413977730fa590a759d2eca3d2ac611fd5ec.tar.gz cpython-736c413977730fa590a759d2eca3d2ac611fd5ec.tar.bz2 |
[3.12] bpo-38157: Add example about per file output for mock_open. (GH-16090) (#109071)
bpo-38157: Add example about per file output for mock_open. (GH-16090)
(cherry picked from commit e183a71eef1ec3ac86bb4d81a158c21d6f1a783b)
Co-authored-by: Karthikeyan Singaravelan <tir.karthi@gmail.com>
Co-authored-by: Stanley <46876382+slateny@users.noreply.github.com>
Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
Co-authored-by: Hugo van Kemenade <hugovk@users.noreply.github.com>
Diffstat (limited to 'Doc/library')
-rw-r--r-- | Doc/library/unittest.mock-examples.rst | 24 |
1 files changed, 24 insertions, 0 deletions
diff --git a/Doc/library/unittest.mock-examples.rst b/Doc/library/unittest.mock-examples.rst index 744fc9d..34f343e 100644 --- a/Doc/library/unittest.mock-examples.rst +++ b/Doc/library/unittest.mock-examples.rst @@ -360,6 +360,30 @@ of arbitrary attributes as well as the getting of them then you can use *spec_set* instead of *spec*. +Using side_effect to return per file content +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +:func:`mock_open` is used to patch :func:`open` method. :attr:`~Mock.side_effect` +can be used to return a new Mock object per call. This can be used to return different +contents per file stored in a dictionary:: + + DEFAULT = "default" + data_dict = {"file1": "data1", + "file2": "data2"} + + def open_side_effect(name): + return mock_open(read_data=data_dict.get(name, DEFAULT))() + + with patch("builtins.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("file3") as file2: + assert file2.read() == "default" + Patch Decorators ---------------- |