I am using pythons mock.patch and would like to change the return value for each call. Here is a caution: the patch function has no inputs, so I cannot change the return value based on input.
Here is my code for reference.
def get_boolean_response(): response = io.prompt('y/n').lower() while response not in ('y', 'n', 'yes', 'no'): io.echo('Not a valid input. Try again']) response = io.prompt('y/n').lower() return response in ('y', 'yes')
My test code is:
@mock.patch('io') def test_get_boolean_response(self, mock_io):
io.prompt is just a platform-independent (python 2 and 3) version of the "input". Therefore, in the end, I try to mock users. I tried using a list for the return value, but this does not work.
You can see that if the return value is something invalid, I will just get an infinite loop here. So I need a way to ultimately change the return value, so my test actually ends.
(another possible way to answer this question might be to explain how I could simulate user input in a unit test)
Do not duplicate this question mainly because I do not have the ability to change the input.
One of the comments from the answer to this question corresponds to the same lines, but no answer / comment was provided.
python unit-testing mocking python-mock
Nick Humrich Jul 22 '14 at 20:25 2014-07-22 20:25
source share