I have a script.py
file:
# in script.py
def my_basic_function(value, c):
return c(value).words()
class BasicClass:
def __init__(self, val):
self.val = val
def words():
return self.val
and a test.py
file:
# in test.py
from mock import patch
from script import my_basic_function, BasicClass
def third_function(self,):
return "not {}".format(self.val)
def fourth_function():
return "not ponies"
def init_mock(self, val):
self.val = val
@patch('script.BasicClass.words', third_function)
@patch('script.BasicClass.__init__', init_mock)
def test_my_basic_function():
assert my_basic_function("ponies", BasicClass) == "not ponies"
that I can run using pytest test.py
from the command line successfully.
If I want to use side_effect
in my @patch
, I have to do things a little differently:
@patch('script.BasicClass.words', side_effect = fourth_function)
@patch('script.BasicClass.__init__', init_mock)
def test_my_basic_function(amock):
assert my_basic_function("ponies", BasicClass) == "not ponies"
i.e., I have to:
- add an argument to
test_my_basic_function
that I never use. - call
fourth_function
rather thanthird_function
, as I cannot use any class instance variables.
What is the difference between patching in these two ways?