We have been using Mock for python for a while.
Now, we have a situation in which we want to mock a function
def foo(self, my_param):
#do something here, assign something to my_result
return my_result
Normally, the way to mock this would be (assuming foo being part of an object)
self.foo = MagicMock(return_value="mocked!")
Even, if i call foo() a couple of times i can use
self.foo = MagicMock(side_effect=["mocked once", "mocked twice!"])
Now, I am facing a situation in which I want to return a fixed value when the input parameter has a particular value. So if let's say "my_param" is equal to "something" then I want to return "my_cool_mock"
This seems to be available on mockito for python
when(dummy).foo("something").thenReturn("my_cool_mock")
I have been searching on how to achieve the same with Mock with no success?
Any ideas?
I know its quite an old question, might help as an improvement using python lamdba
As indicated at Python Mock object with method called multiple times
A solution is to write my own side_effect
That does the trick
You can also use
partial
fromfunctools
if you want to use a function that takes parameters but the function you are mocking does not. E.g. like this:This will return a callable that doesn't accept parameters (like Django's timezone.now()), but my mock_year function does.
Side effect takes a function (which can also be a lambda function), so for simple cases you may use:
I've ended up here looking for "how to mock a function based on input arguments" and I finally solved this creating a simple aux function:
Now:
Hope this will help someone!
Just to show another way of doing it: