Following the approach in this answer I am able to override the default values of a function using the approach below, see test_foo_defaults
.
main.py:
def bar(x):
return x * 2
def foo(a, b=bar, c=4):
return f'{a} {b(a)} {c}'
main_test.py
import unittest
from unittest import mock
from unittest.mock import MagicMock
import main
def test_foo():
assert '3 6 4' == main.foo(3)
def test_foo_defaults():
m = MagicMock()
m.return_value = 12
with mock.patch.object(main.foo, '__defaults__', (m, 7)):
assert '3 12 7' == main.foo(3)
@mock.patch.object(main.foo.__defaults__, 0)
def test_foo_defaults_2(m):
m.return_value = 12
assert '3 12 5' == main.foo(3)
However, I'd like to be able to do something like test_foo_defaults2
, in which I only override one default parameter and get a handle to it as a mock passed to my test function. test_foo_defaults2
does not work unfortunately, but fails with: TypeError: getattr(): attribute name must be string
.
Are there any solutions to this?