Skip to content

Commit e183a71

Browse files
tirkarthislatenyJelleZijlstrahugovk
authored
bpo-38157: Add example about per file output for mock_open. (#16090)
Co-authored-by: Stanley <[email protected]> Co-authored-by: Jelle Zijlstra <[email protected]> Co-authored-by: Hugo van Kemenade <[email protected]>
1 parent 3e53ac9 commit e183a71

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

Doc/library/unittest.mock-examples.rst

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -360,6 +360,30 @@ of arbitrary attributes as well as the getting of them then you can use
360360
*spec_set* instead of *spec*.
361361

362362

363+
Using side_effect to return per file content
364+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
365+
366+
:func:`mock_open` is used to patch :func:`open` method. :attr:`~Mock.side_effect`
367+
can be used to return a new Mock object per call. This can be used to return different
368+
contents per file stored in a dictionary::
369+
370+
DEFAULT = "default"
371+
data_dict = {"file1": "data1",
372+
"file2": "data2"}
373+
374+
def open_side_effect(name):
375+
return mock_open(read_data=data_dict.get(name, DEFAULT))()
376+
377+
with patch("builtins.open", side_effect=open_side_effect):
378+
with open("file1") as file1:
379+
assert file1.read() == "data1"
380+
381+
with open("file2") as file2:
382+
assert file2.read() == "data2"
383+
384+
with open("file3") as file2:
385+
assert file2.read() == "default"
386+
363387

364388
Patch Decorators
365389
----------------

0 commit comments

Comments
 (0)