Patch builtins.open so that it returns StringIO object. :param side_effect: Additional side effect for when the open context is entered. Example:: >>> with mock.open(io.BytesIO) as open_fh: ... something_opening_and_writing_bytes_to_a_file() ... self.a
(side_effect=None)
| 737 | |
| 738 | @contextmanager |
| 739 | def open(side_effect=None): |
| 740 | """Patch builtins.open so that it returns StringIO object. |
| 741 | :param side_effect: Additional side effect for when the open context |
| 742 | is entered. |
| 743 | Example:: |
| 744 | >>> with mock.open(io.BytesIO) as open_fh: |
| 745 | ... something_opening_and_writing_bytes_to_a_file() |
| 746 | ... self.assertIn(b'foo', open_fh.getvalue()) |
| 747 | """ |
| 748 | with patch('builtins.open') as open_: |
| 749 | with _mock_context(open_) as context: |
| 750 | if side_effect is not None: |
| 751 | context.__enter__.side_effect = side_effect |
| 752 | val = context.__enter__.return_value = WhateverIO() |
| 753 | val.__exit__ = Mock() |
| 754 | yield val |
| 755 | |
| 756 | |
| 757 | @contextmanager |
no test coverage detected