Python mock multiple return values
Get a quick win by creating a sequence of return values for a mock using unittest.mock
's side_effect
. Straightaway apply it to the mock's configuration:
Simply strap side_effect
to an iterable armed with the desired return values. Each call to mock_func
whisks away the next item.
Keep your gadgets handy for a more sophisticated response logic, deploy an iterator or a function as the side_effect
. This enhances test versatility and mimics dynamic reaction scenarios more closely.
Harnessing iterators and iterables as side_effects
Spawn a Mock with an iterable
Commandeer a list or any iterable directly into side_effect
to yield one value per call:
Now, mock_obj.some_method()
will have an identity crisis—returns different Batman quotes at each call.
Dial up precision with an iterator
Collaborate with iter()
alongside patch()
to simulate user input via side_effect
:
The iterator state stands guard across calls, churning out the specified returns in tests.
Extensive test coverage for variable return values
Maneuver function calls without inputs
When the function doesn't bother about inputs, ensure uniform returns for each call:
Ratify function calls and outputs
After donning the side_effect
attire, concoct tests to validate:
- Function dials the right number of times.
- The output sequence plugs into the
side_effect
playlist.
Blasting exceptions using side_effects
To pull the pin on exceptions in a careful order along with valid return values:
Remember if an exception blasts off, calls made post the explosion do not proceed unless caught mid-air within the test.
Navigating the parameter maze
A spectrum of inputs, custom responses
When different inputs command different responses:
The side_effect
function here handles various tastes, mapping them to custom return values.
Dynamically altering the return flight
To mimic real-time maneuvers based on call history or external changes in course:
This graphs the trajectory of a process over a period of time.
Conducting an orchestra of mock objects with side effects
Patching on instance methods
When photographing instance methods, aim right:
Amplifying class methods and static methods
Class and static methods must be patched backstage:
Directing property symphonies with side_effect
Property values reflect their changing colors using side_effect as a PropertyMock
:
Was this article helpful?