Skip to content

Instantly share code, notes, and snippets.

@adammartinez271828
Last active February 28, 2024 18:52
Show Gist options
  • Select an option

  • Save adammartinez271828/137ae25d0b817da2509c1a96ba37fc56 to your computer and use it in GitHub Desktop.

Select an option

Save adammartinez271828/137ae25d0b817da2509c1a96ba37fc56 to your computer and use it in GitHub Desktop.
Create a mock "open" that will mock open multiple files in sequence
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
@rubenobbink
Copy link

Great!

@ang-d
Copy link

ang-d commented Feb 22, 2022

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment