Last active
February 28, 2024 18:52
-
-
Save adammartinez271828/137ae25d0b817da2509c1a96ba37fc56 to your computer and use it in GitHub Desktop.
Create a mock "open" that will mock open multiple files in sequence
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from unittest.mock import mock_open | |
| def multi_mock_open(*file_contents): | |
| """Create a mock "open" that will mock open multiple files in sequence | |
| Args: | |
| *file_contents ([str]): a list of file contents to be returned by open | |
| Returns: | |
| (MagicMock) a mock opener that will return the contents of the first | |
| file when opened the first time, the second file when opened the | |
| second time, etc. | |
| """ | |
| mock_files = [mock_open(read_data=content).return_value for content in file_contents] | |
| mock_opener = mock_open() | |
| mock_opener.side_effect = mock_files | |
| return mock_opener | |
Great!
Thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks, this was useful. I eventually came up with this: