Reputation: 241
I am writing a unit test and I am trying to check that function was called with the right arguments. I was told that I can do this with mocking. This is my code
import pytest
from mock import patch
import attr
def adjust(x):
if x is None:
return 0
return x
@attr.s
class Pater():
only_argument = attr.ib(type=int,converter = adjust)
def foo(pass_only):
yield Pater(pass_only)
@patch("this_file.Pater")
def test_foo(mock_Pater):
foo(None)
mock_Pater.assert_called_with(None)
But I am getting the following error
E AssertionError: expected call not found.
E Expected: Pater(None)
E Actual: not called.
Could you advise me on how to do it correctly?
Upvotes: 0
Views: 83
Reputation: 71454
Your test does not, indeed, call/instantiate Pater
, because foo()
is a Pater
generator, and you haven't pulled any items from it yet. To put it another way, the code inside the yield
isn't executed until you iterate over the return value of foo()
.
Change your test to:
@patch("this_file.Pater")
def test_foo(mock_Pater):
next(foo(None))
mock_Pater.assert_called_with(None)
and it will pass.
Upvotes: 2