Verification is important for checking that an interaction did or did not happen, or if it happened a specific amount of times. It can also allow for checking that interactions happened in a particular order.
Typemock currently only has quite limited verification, but it is good for most use cases.
Given the following class to mock:
class MyThing:
def convert_int_to_str(self, number: int) -> str:
pass
We can verify method interactions in the following ways:
We can assert that an interaction happened at least once.
with tmock(MyThing) as my_thing_mock:
when(my_thing_mock.convert_int_to_str(match.anything())).then_return("something")
# Logic under test is called.
verify(my_thing_mock).convert_int_to_str(3)
We can assert that an interaction happened a specific number of times.
with tmock(MyThing) as my_thing_mock:
when(my_thing_mock.convert_int_to_str(match.anything())).then_return("something")
# Logic under test is called.
verify(my_thing_mock, exactly=2).convert_int_to_str(3)
We can assert that an interaction never happened by checking for 0 calls.
with tmock(MyThing) as my_thing_mock:
when(my_thing_mock.convert_int_to_str(match.anything())).then_return("something")
# Logic under test is called.
verify(my_thing_mock, exactly=0).convert_int_to_str(3)
And all of the previous examples have been verifying calls with specific args. We can also use the match.anything matcher to check for any interactions.
with tmock(MyThing) as my_thing_mock:
when(my_thing_mock.convert_int_to_str(match.anything())).then_return("something")
# Logic under test is called.
verify(my_thing_mock).convert_int_to_str(match.anything())
Given the following class to mock:
class MyThing:
name: str = "anonymous"
We can verify interactions with its attribute as follows.
my_thing_mock = tmock(MyThing)
# Logic under test is called.
verify(my_thing_mock).name
my_thing_mock = tmock(MyThing)
# Logic under test is called.
verify(my_thing_mock, exactly=2).name
my_thing_mock = tmock(MyThing)
# Logic under test is called.
verify(my_thing_mock).name = 2
my_thing_mock = tmock(MyThing)
# Logic under test is called.
verify(my_thing_mock).name = match.anything()
my_thing_mock = tmock(MyThing)
# Logic under test is called.
verify(my_thing_mock, exactly=1).name = 2