I am new to mock and and trying to work with side_effects.
I am trying to set the return value of a method of a mocked class based on the argument said method was called with. In the below code, I am trying to set the return value of some_function
when having mocked MyClass
.
# application.py
from my_module.my_submodule import MyClass
def my_function(var1):
instance = MyClass()
instance.some_function(var1)
and my testing file
# test_application.py
import mock
import application
def test_my_function():
with mock.patch('application.MyClass') as MockClass:
MockClass.return_value.my_function.return_value = some_return
application.my_function(var1)
This works such that some_function
now returns some_return
, but I would like to have a function in place of some_return
which takes the argument var1
that the function is called with.
The problem is that I don't know how to define the mock to anticipate the calling argument of some_function
.
I have experimented with what is discussed in this post changing the side effect of a mock object's method created with patch, but I can't for the life of me figure out how to format it.
I have tried something like this
# test_application.py
import mock
import application
def test_my_function():
with mock.patch('application.MyClass') as MockClass:
MockClass.return_value.my_function.return_value = some_return
# Breaking very long line, in my code it's actually one line.
MockDataPrep.return_value.extract_preprocessed_citizen_data.\
side_effect =\
mock.MagicMock(side_effect=my_side_effect)
application.my_function(var1)
where the function my_side_effect
looks like this:
def my_side_effect(var1):
return_val = some_manipulation_of_var1(var1)
if something:
return `abc`
else:
raise LookupError
but it doesn't seem that the my_side_effect
is ever entered (tried with print statements inside of it). How would I format this?
Aucun commentaire:
Enregistrer un commentaire