Part of my problem was a misunderstanding of patch's behavior. The context manager I set up is returning an instance of the __main__.Foo
mock, not the same instance used in my_func()
. To put it another way, even when I was able to mock Foo
properly, without autospec, I couldn't execute assert_called_once_with()
over any of its methods: It wasn't the same object.
One solution is to mock the method itself. This works:
def test_my_func(self):
bar = None
with patch('__main__.Foo.methodB') as mock_methodB:
my_func(bar)
mock_methodB.assert_called_once_with()
Another method would be modifying my_func()
to return foo:
def my_func(bar):
foo = Foo(bar)
if foo.bar:
foo.methodA()
foo.methodB()
return foo
Because the function returns the mock under test, the following should work:
def test_my_func(self):
bar = None
with patch('__main__.Foo', spec=True, bar=None):
foo = my_func(bar)
assert foo.methodB.called
assert not foo.methodA.called