I am adding testing to a pipeline project, code is already written and in production so it cannot be changed to accommodate the tests.
In simplest terms, if I have a function like so:
def other_foo():
return 1
def foo():
res = other_foo()
return res
In practicality, the other_foo
call will return a variety of responses, but for testing, I want to create a fixed response to test foo
.
So in my test I want to create a fixed response to other_foo
of 2. and my test evaluation to be something like:
def test_foo():
# some mocking or nesting handle here for other_foo
res = foo()
assert res == 2
CodePudding user response:
Use the patch
decorator from unitest.mock
and patch your module local variable.
from your.module import foo
from unitest.mock import patch
@patch('your.module.other_foo')
def test_foo(mock_other_foo):
mock_other_foo.return_value = 3
assert foo() == 3
mock_other_foo.return_value = 42
assert foo() == 42