Reputation: 433
I want to test a function that makes use of the builtins.open function and want to return a value depending on which path was provided. So far my function looks like this:
@pytest.fixture
def mock_open(self,mocker):
mock_file = mocker.patch('builtins.open', return_value=StringIO("mock open"))
return mock_file
Is there a way to say "if path==a then return "mock a", else return "mock b"?
Upvotes: 0
Views: 1789
Reputation: 10719
Use side_effect to intercept the call to open()
and act accordingly based on the file
parameter.
@pytest.fixture
def mock_open(self, mocker):
def _mock_open(file, *args, **kwargs):
if file == "a":
return StringIO("For a")
return StringIO("For b")
mock_file = mocker.patch('builtins.open', side_effect=_mock_open)
return mock_file
Upvotes: 2