Skip to content

API reference

mocker(target=None, *, spec=None, patch_class=False, **kwargs)

Main entrypoint for chainmock.

Depending on the arguments you pass to mocker function, it provides different functionality. Supported functionalities are partial mocking (and spying), stubbing, and patching. See detailed explanations below.

Partial mocking

If mocker is invoked with an object (eg. class, instance, module), the named members (attributes) on the object (target) can be mocked or spied individually. For example, by calling mocker(SomeClass) you are setting the target to a class. The original object is not modified until you explicitly spy or mock it's members.

Stubbing

If mocker is invoked without a target, a stub is created. For example, by calling mocker(). The created stub doesn't have any methods or attributes until you explicitly set them.

Patching

If the given target is a string, the target is imported and the specified object is replaced with a mock. The string should be in form 'package.module.ClassName' and the target must be importable from the environment you are calling mocker. As an example, mocker('some_module.SomeClass') would replace the SomeClass class in the module some_module. After patching the object, you can set assertions and return values on the mock that replaced the object.

Patching is useful especially when you want to replace all the new instances of a class with a mock. Therefore if you patch a class, chainmock patches the class instances by default. If you wish to patch the class instead, set patch_class argument to True. If you do not need to patch new instances of a class, most use cases can be covered with partial mocking.

For more details about patching see: unittest.mock.html#patch

Examples:

Partially mock the Teapot class:

>>> # First let's fill a teapot and boil the water without mocking
>>> teapot = Teapot()
>>> teapot.state
'empty'
>>> teapot.fill()
>>> teapot.state
'full'
>>> teapot.boil()
>>> teapot.state
'boiling'
>>> # Now let's try the same thing but also mock the boil call
>>> mocker(Teapot).mock("boil")
<chainmock._api.Assert object at ...>
>>> teapot = Teapot()
>>> teapot.state
'empty'
>>> teapot.fill()  # fill still works because only boil method is mocked
>>> teapot.state
'full'
>>> teapot.boil()  # state is not updated because boil method is mocked
>>> teapot.state
'full'

Create a stub and attach methods to it:

>>> stub = mocker()
>>> stub.mock("my_method").return_value("It works!")
<chainmock._api.Assert object at ...>
>>> stub.mock("another_method").side_effect(RuntimeError("Oh no!"))
<chainmock._api.Assert object at ...>
>>> stub.my_method()
'It works!'
>>> stub.another_method()
Traceback (most recent call last):
  ...
RuntimeError: Oh no!

Replace all the instances of SomeClass with a mock by patching it:

>>> class SomeClass:
...    def method(self, arg):
...        pass
...
>>> mocked = mocker("__main__.SomeClass")
>>> # SomeClass instances are now replaced by a mock
>>> some_class = SomeClass()
>>> some_class.method("foo")
>>> # We can change return values, assert call counts or arguments
>>> mocked.mock("method").return_value("mocked")
<chainmock._api.Assert object at ...>

Parameters:

Name Type Description Default
target Optional[Union[str, Any]]

The target to mock or spy. By leaving out the target, a stub is created. If the target is a string, the object in the given path is mocked and if the target is any other object like class or module, you can mock and spy individual functions and methods using the returned mock instance.

None
spec Optional[Any]

Spec acts as the specification for the created mock objects. It can be either a list of strings or an existing object (a class or instance). Accessing any attribute not in the given spec raises an AttributeError. Spec can be useful if you want to create stubs with a certain spec. Otherwise it is usually not needed because spec is automatically set from the given target object.

If spec is an object then Mock.__class__ returns the class of the spec object. This allows mocks to pass isinstance tests.

None
patch_class bool

By default, patching an object (setting target to a string) allows mocking attributes of the instance of a given target class. If you want to mock the class itself, instead of it's instance, set this to True. Note that it is usually easier to just use partial mocking if you need to patch the class.

False
**kwargs Any

You can give arbitrary keyword arguments to quickly set mocked attributes and properties.

{}

Returns:

Type Description
Mock

Mock instance.

Mock

Mock allows mocking and spying mocked and patched objects.

Mock should not be initialized directly. Use mocker function instead.

get_mock(self)

Return the unittest mock associated with this Mock object.

Normally, there should not be a need call this function, but it can be used as an escape hatch when something is not possible with chainmock and you need to access the underlying standard library unittest mock object directly.

Examples:

Mocking builtin open function:

>>> mock_file = mocker()
>>> mock_file.mock("read").return_value("mocked").called_once()
<chainmock._api.Assert object at ...>
>>> mock_open = mocker("builtins.open").get_mock()
>>> mock_open.return_value.__enter__ = mock_file
>>> with open("file_name") as file:
...    file.read()
'mocked'

mock(self, name, *, create=False, force_property=False, force_async=False)

Mock an attribute.

The given attribute is mocked and the mock catches all the calls to it. If no return value is set, None is returned by default.

Examples:

Assert that the method add_tea was called once:

>>> teapot = Teapot()
>>> teapot.add_tea("white tea")
'loose white tea'
>>> mocker(teapot).mock("add_tea").called_once()
<chainmock._api.Assert object at ...>
>>> teapot.add_tea("white tea")

Replace the return value of the add_tea method:

>>> teapot = Teapot()
>>> teapot.add_tea("green tea")
'loose green tea'
>>> mocker(teapot).mock("add_tea").return_value("mocked")
<chainmock._api.Assert object at ...>
>>> teapot.add_tea("green tea")
'mocked'

Assert that the method add_tea was called with a specific argument while also replacing the return value:

>>> teapot = Teapot()
>>> teapot.add_tea("white tea", loose=False)
'bagged white tea'
>>> mocker(teapot).mock("add_tea").match_args_last_call(
...     "green tea"
... ).return_value("mocked")
<chainmock._api.Assert object at ...>
>>> teapot.add_tea("green tea", loose=True)
'mocked'

Parameters:

Name Type Description Default
name str

Attribute name to mock.

required
create bool

Force creation of the attribute if it does not exist. By mocking non-existing attributes raises an AttributeError. If you want force the creation and ignore the error, set this to True. This can be useful for testing dynamic attributes set during runtime.

False
force_property bool

Force the mock to be a PropertyMock. This can be used to create properties on stubs or force the mock to be a PropertyMock if the automatic detection from spec does not work.

False
force_async bool

Force the mock to be a AsyncMock. This can be used to create async methods on stubs or force the mock to be a AsyncMock if the automatic detection from spec does not work.

False

Returns:

Type Description
Assert

Assert instance.

Exceptions:

Type Description
ValueError

Raised if the given attribute name is empty.

RuntimeError

If trying to mock a spied attribute.

spy(self, name)

Spy an attribute.

This wraps the given attribute so that functions or methods still return their original values and work as if they were not mocked. With spies, you can assert that a function or method was called without mocking it.

Examples:

Assert that the method add_tea was called once:

>>> teapot = Teapot()
>>> teapot.add_tea("white tea")
'loose white tea'
>>> mocker(teapot).spy("add_tea").called_once()
<chainmock._api.Assert object at ...>
>>> teapot.add_tea("white tea")
'loose white tea'

Assert that the method add_tea was called with specific arguments:

>>> teapot = Teapot()
>>> teapot.add_tea("white tea", loose=False)
'bagged white tea'
>>> mocker(teapot).spy("add_tea").called_last_with("green tea", loose=True)
<chainmock._api.Assert object at ...>
>>> teapot.add_tea("green tea", loose=True)
'loose green tea'

Parameters:

Name Type Description Default
name str

Attribute name to spy.

required

Returns:

Type Description
Assert

Assert instance.

Exceptions:

Type Description
ValueError

Raised if the given attribute name is empty.

RuntimeError

If trying to spy stubs or patched objects. Also raised if trying to spy a mocked attribute.

Assert

Assert allows creation of assertions for mocks.

The created assertions are automatically validated at the end of a test.

Assert should not be initialized directly. Use mocker function instead.

all_awaits_with(self, *args, **kwargs)

Assert that all awaits have the specified arguments.

The assert passes if all awaits have been made with the given arguments.

Examples:

>>> mocker(teapot).mock("timer").all_calls_with(5)
<chainmock._api.Assert object at ...>
>>> asyncio.run(teapot.timer(5))
>>> asyncio.run(teapot.timer(5))

Parameters:

Name Type Description Default
*args Any

Expected positional arguments.

()
**kwargs Any

Expected keyword arguments.

{}

Returns:

Type Description
Assert

Assert instance so that calls can be chained.

all_calls_with(self, *args, **kwargs)

Assert that all calls have the specified arguments.

The assert passes if all calls have been made with the given arguments.

Examples:

>>> mocker(Teapot).mock("add_tea").all_calls_with("black")
<chainmock._api.Assert object at ...>
>>> Teapot().add_tea("black")
>>> Teapot().add_tea("black")

Parameters:

Name Type Description Default
*args Any

Expected positional arguments.

()
**kwargs Any

Expected keyword arguments.

{}

Returns:

Type Description
Assert

Assert instance so that calls can be chained.

any_await_with(self, *args, **kwargs)

Assert that the mock has been awaited with the specified arguments.

The assert passes if the mock has ever been awaited with given arguments.

Wrapper for unittest.mock.AsyncMock.assert_any_await.

For more details see: unittest.mock.AsyncMock.assert_any_await

Examples:

>>> mocker(teapot).mock("timer").any_call_with(5)
<chainmock._api.Assert object at ...>
>>> asyncio.run(teapot.timer(5))
>>> asyncio.run(teapot.timer(3))

Parameters:

Name Type Description Default
*args Any

Expected positional arguments.

()
**kwargs Any

Expected keyword arguments.

{}

Returns:

Type Description
Assert

Assert instance so that calls can be chained.

any_call_with(self, *args, **kwargs)

Assert that the mock has been called with the specified arguments.

The assert passes if the mock has ever been called with given arguments.

Wrapper for unittest.mock.Mock.assert_any_call.

For more details see: unittest.mock.Mock.assert_any_call

Examples:

>>> mocker(Teapot).mock("add_tea").any_call_with("black")
<chainmock._api.Assert object at ...>
>>> Teapot().add_tea("oolong")
>>> Teapot().add_tea("black")

Parameters:

Name Type Description Default
*args Any

Expected positional arguments.

()
**kwargs Any

Expected keyword arguments.

{}

Returns:

Type Description
Assert

Assert instance so that calls can be chained.

await_count(self, await_count)

Assert that the mock was awaited the specified number of times.

Examples:

>>> mocker(teapot).mock("open").await_count(3)
<chainmock._api.Assert object at ...>
>>> asyncio.run(teapot.open())
>>> asyncio.run(teapot.open())
>>> asyncio.run(teapot.open())

Parameters:

Name Type Description Default
await_count int

Expected await count.

required

Returns:

Type Description
Assert

Assert instance so that calls can be chained.

await_count_at_least(self, await_count)

Assert that the mock was awaited at least the specified number of times.

Examples:

Assert that the method open was awaited at least once:

>>> mocker(teapot).mock("open").await_count_at_least(1)
<chainmock._api.Assert object at ...>
>>> asyncio.run(teapot.open())
>>> asyncio.run(teapot.open())

Assert that the method close was awaited at least once but not more than twice:

>>> mocker(teapot).mock("close").await_count_at_least(1).await_count_at_most(2)
<chainmock._api.Assert object at ...>
>>> asyncio.run(teapot.close())
>>> asyncio.run(teapot.close())

Parameters:

Name Type Description Default
await_count int

Expected await count.

required

Returns:

Type Description
Assert

Assert instance so that calls can be chained.

await_count_at_most(self, await_count)

Assert that the mock was awaited at most the specified number of times.

Examples:

Assert that the method open was awaited at most twice:

>>> mocker(teapot).mock("open").await_count_at_most(2)
<chainmock._api.Assert object at ...>
>>> asyncio.run(teapot.open())
>>> asyncio.run(teapot.open())

Assert that the method close was awaited at most twice and at least once:

>>> mocker(teapot).mock("close").await_count_at_most(2).await_count_at_least(1)
<chainmock._api.Assert object at ...>
>>> asyncio.run(teapot.close())
>>> asyncio.run(teapot.close())

Parameters:

Name Type Description Default
await_count int

Expected await count.

required

Returns:

Type Description
Assert

Assert instance so that calls can be chained.

awaited(self)

Assert that the mock was awaited at least once.

Wrapper for unittest.mock.AsyncMock.assert_awaited.

For more details see: unittest.mock.AsyncMock.assert_awaited

Examples:

>>> mocker(Teapot).mock("timer").awaited()
<chainmock._api.Assert object at ...>
>>> asyncio.run(Teapot().timer())

Returns:

Type Description
Assert

Assert instance so that calls can be chained.

awaited_last_with(self, *args, **kwargs)

Assert that the most recent await was with the specified arguments.

Wrapper for unittest.mock.AsyncMock.assert_awaited_with.

For more details see: unittest.mock.AsyncMock.assert_awaited_with

Examples:

>>> mocker(teapot).mock("timer").awaited_last_with(minutes=10)
<chainmock._api.Assert object at ...>
>>> asyncio.run(teapot.timer(minutes=10))

Parameters:

Name Type Description Default
*args Any

Expected positional arguments.

()
**kwargs Any

Expected keyword arguments.

{}

Returns:

Type Description
Assert

Assert instance so that calls can be chained.

awaited_once(self)

Assert that the mock was awaited exactly once.

Provides similar functionality to unittest.mock.AsyncMock.assert_awaited_once.

For more details see: unittest.mock.AsyncMock.assert_awaited_once

Examples:

>>> mocker(Teapot).mock("open").awaited_once()
<chainmock._api.Assert object at ...>
>>> asyncio.run(Teapot().open())

Returns:

Type Description
Assert

Assert instance so that calls can be chained.

awaited_once_with(self, *args, **kwargs)

Assert that the mock was awaited exactly once with the specified arguments.

Wrapper for unittest.mock.AsyncMock.assert_awaited_once_with.

For more details see: unittest.mock.AsyncMock.assert_awaited_once_with

Examples:

>>> mocker(teapot).mock("timer").called_once_with(5)
<chainmock._api.Assert object at ...>
>>> asyncio.run(teapot.timer(5))

Parameters:

Name Type Description Default
*args Any

Expected positional arguments.

()
**kwargs Any

Expected keyword arguments.

{}

Returns:

Type Description
Assert

Assert instance so that calls can be chained.

awaited_twice(self)

Assert that the mock was awaited exactly twice.

Examples:

>>> mocker(teapot).mock("timer").awaited_twice()
<chainmock._api.Assert object at ...>
>>> asyncio.run(teapot.timer(1))
>>> asyncio.run(teapot.timer(2))

Returns:

Type Description
Assert

Assert instance so that calls can be chained.

call_count(self, call_count)

Assert that the mock was called the specified number of times.

Examples:

>>> mocker(teapot).mock("pour").call_count(3)
<chainmock._api.Assert object at ...>
>>> teapot.pour()
>>> teapot.pour()
>>> teapot.pour()

Parameters:

Name Type Description Default
call_count int

Expected call count.

required

Returns:

Type Description
Assert

Assert instance so that calls can be chained.

call_count_at_least(self, call_count)

Assert that the mock was called at least the specified number of times.

Examples:

Assert that the method pour was called at least once:

>>> mocker(teapot).mock("pour").call_count_at_least(1)
<chainmock._api.Assert object at ...>
>>> teapot.pour()
>>> teapot.pour()

Assert that the method boil was called at least once but not more than twice:

>>> mocker(teapot).mock("boil").call_count_at_least(1).call_count_at_most(2)
<chainmock._api.Assert object at ...>
>>> teapot.boil()
>>> teapot.boil()

Parameters:

Name Type Description Default
call_count int

Expected call count.

required

Returns:

Type Description
Assert

Assert instance so that calls can be chained.

call_count_at_most(self, call_count)

Assert that the mock was called at most the specified number of times.

Examples:

Assert that the method pour was called at most twice:

>>> mocker(teapot).mock("pour").call_count_at_most(2)
<chainmock._api.Assert object at ...>
>>> teapot.pour()
>>> teapot.pour()

Assert that the method boil was called at most twice and at least once:

>>> mocker(teapot).mock("boil").call_count_at_most(2).call_count_at_least(1)
<chainmock._api.Assert object at ...>
>>> teapot.boil()
>>> teapot.boil()

Parameters:

Name Type Description Default
call_count int

Expected call count.

required

Returns:

Type Description
Assert

Assert instance so that calls can be chained.

called(self)

Assert that the mock was called at least once.

Wrapper for unittest.mock.Mock.assert_called.

For more details see: unittest.mock.Mock.assert_called

Examples:

>>> mocker(Teapot).mock("pour").called()
<chainmock._api.Assert object at ...>
>>> Teapot().pour()

Returns:

Type Description
Assert

Assert instance so that calls can be chained.

called_last_with(self, *args, **kwargs)

Assert that the most recent call was made with the specified arguments.

Wrapper for unittest.mock.Mock.assert_called_with.

For more details see: unittest.mock.Mock.assert_called_with

Examples:

>>> mocker(Teapot).mock("add_tea").called_last_with("green", loose=True)
<chainmock._api.Assert object at ...>
>>> Teapot().add_tea("green", loose=True)

Parameters:

Name Type Description Default
*args Any

Expected positional arguments.

()
**kwargs Any

Expected keyword arguments.

{}

Returns:

Type Description
Assert

Assert instance so that calls can be chained.

called_once(self)

Assert that the mock was called exactly once.

Provides similar functionality to unittest.mock.Mock.assert_called_once.

For more details see: unittest.mock.Mock.assert_called_once

Examples:

>>> mocker(Teapot).mock("boil").called_once()
<chainmock._api.Assert object at ...>
>>> Teapot().boil()

Returns:

Type Description
Assert

Assert instance so that calls can be chained.

called_once_with(self, *args, **kwargs)

Assert that the mock was called exactly once and that call was with the specified arguments.

Wrapper for unittest.mock.Mock.assert_called_once_with.

For more details see: unittest.mock.Mock.assert_called_once_with

Examples:

>>> mocker(Teapot).mock("add_tea").called_once_with("puehr")
<chainmock._api.Assert object at ...>
>>> Teapot().add_tea("puehr")

Parameters:

Name Type Description Default
*args Any

Expected positional arguments.

()
**kwargs Any

Expected keyword arguments.

{}

Returns:

Type Description
Assert

Assert instance so that calls can be chained.

called_twice(self)

Assert that the mock was called exactly twice.

Examples:

>>> mocker(teapot).mock("pour").called_twice()
<chainmock._api.Assert object at ...>
>>> teapot.pour()
>>> teapot.pour()

Returns:

Type Description
Assert

Assert instance so that calls can be chained.

get_mock(self)

Return the unittest mock associated with this Assert object.

This method can be used if you want to access the underlying unittest mock directly. Normally, there should not be a need for this, but you can use this method if you prefer to call the assertion methods directly on the unittest mock instead of using chainmock's methods.

One difference between calling assertion methods on the unittest mock and chainmock is that unittest mock validates the assertions right away whereas chainmock verifies the assertions after the test execution during test teardown. Therefore, unittest mock allows making assertions before the test teardown. If you are not sure what this means, see the examples section.

Examples:

Mock the add_tea method and call assertions directly on unittest mock:

>>> teapot = Teapot()
>>> mock = mocker(teapot).mock("add_tea").get_mock()
>>> # Using get_mock allows making assertions before test teardown
>>> mock.assert_not_called()
>>> teapot.add_tea("green")
>>> mock.assert_called_once_with("green")

The above code can be written without calling get_mock as follows:

>>> teapot = Teapot()
>>> mocker(teapot).mock("add_tea").called_once_with("green")
<chainmock._api.Assert object at ...>
>>> teapot.add_tea("green")

Returns:

Type Description
AnyMock

Python unittest mock (AsyncMock, MagicMock, or PropertyMock).

has_awaits(self, calls, any_order=False)

Assert that the mock has been awaited with the specified calls.

If any_order is True then the calls can be in any order, but they must all be matched. If any_order is False (default) then the calls must be sequential but there can be extra calls before or after the specified calls.

Wrapper for unittest.mock.AsyncMock.assert_has_awaits.

For more details see: unittest.mock.AsyncMock.assert_has_awaits

Examples:

>>> from chainmock.mock import call
>>> mocker(teapot).mock("timer").has_awaits([call(5), call(3)])
<chainmock._api.Assert object at ...>
>>> asyncio.run(teapot.timer(5))
>>> asyncio.run(teapot.timer(3))

Parameters:

Name Type Description Default
calls Sequence[umock._Call]

Expected calls. You can import the call type from chainmock.mock.call or from unittest.mock.call.

required
any_order bool

Indicates if the calls must be sequential (False, default) or in any order (True).

False

Returns:

Type Description
Assert

Assert instance so that calls can be chained.

has_calls(self, calls, any_order=False)

Assert that the mock has been called with the specified calls.

If any_order is True then the calls can be in any order, but they must all be matched. If any_order is False (default) then the calls must be sequential but there can be extra calls before or after the specified calls.

Wrapper for unittest.mock.Mock.assert_has_calls.

For more details see: unittest.mock.Mock.assert_has_calls

Examples:

>>> from chainmock.mock import call
>>> mocker(Teapot).mock("add_tea").has_calls([call("oolong"), call("black")])
<chainmock._api.Assert object at ...>
>>> Teapot().add_tea("oolong")
>>> Teapot().add_tea("black")

Parameters:

Name Type Description Default
calls Sequence[umock._Call]

Expected calls. You can import the call type from chainmock.mock.call or from unittest.mock.call.

required
any_order bool

Indicates if the calls must be sequential (False, default) or in any order (True).

False

Returns:

Type Description
Assert

Assert instance so that calls can be chained.

match_args_all_awaits(self, *args, **kwargs)

Assert that all awaits have at least the specified arguments.

The assert passes if all awaits have at least the given positional or keyword arguments. This can be useful when you want to match just one specific argument and do not care about the rest.

If you want all of the arguments to match, use all_awaits_with method instead.

Examples:

Below assertion passes because all awaits to timer have positional argument 5. Keyword arguments seconds are ignored.

>>> teapot = Teapot()
>>> mocker(teapot).mock("timer").match_args_all_awaits(5)
<chainmock._api.Assert object at ...>
>>> asyncio.run(teapot.timer(5, seconds=15))
>>> asyncio.run(teapot.timer(5, seconds=30))
>>> asyncio.run(teapot.timer(5))

Below assertion passes because all awaits to timer have keyword argument seconds=30. Positional arguments are ignored.

>>> teapot = Teapot()
>>> mocker(teapot).mock("timer").match_args_all_awaits(seconds=30)
<chainmock._api.Assert object at ...>
>>> asyncio.run(teapot.timer(1, seconds=30))
>>> asyncio.run(teapot.timer(5, seconds=30))
>>> asyncio.run(teapot.timer(10, seconds=30))

Parameters:

Name Type Description Default
*args Any

Expected positional arguments.

()
**kwargs Any

Expected keyword arguments.

{}

Returns:

Type Description
Assert

Assert instance so that calls can be chained.

match_args_all_calls(self, *args, **kwargs)

Assert that all calls have at least the specified arguments.

The assert passes if all calls have at least the given positional or keyword arguments. This can be useful when you want to match just one specific argument and do not care about the rest.

If you want all of the arguments to match, use all_calls_with method instead.

Examples:

Below assertion passes because all calls to add_tea have positional argument oolong. Keyword arguments are ignored.

>>> teapot = Teapot()
>>> mocker(teapot).mock("add_tea").match_args_all_calls("oolong")
<chainmock._api.Assert object at ...>
>>> teapot.add_tea("oolong", loose=False)
>>> teapot.add_tea("oolong", loose=True)
>>> teapot.add_tea("oolong")

Below assertion passes because all calls to add_tea have keyword argument loose=True. Positional arguments are ignored.

>>> teapot = Teapot()
>>> mocker(teapot).mock("add_tea").match_args_all_calls(loose=True)
<chainmock._api.Assert object at ...>
>>> teapot.add_tea("oolong", loose=True)
>>> teapot.add_tea("black", loose=True)
>>> teapot.add_tea("green", loose=True)

Parameters:

Name Type Description Default
*args Any

Expected positional arguments.

()
**kwargs Any

Expected keyword arguments.

{}

Returns:

Type Description
Assert

Assert instance so that calls can be chained.

match_args_any_await(self, *args, **kwargs)

Assert that any await has at least the specified arguments.

The assert passes if any await has at least the given positional or keyword arguments. This can be useful when you want to match just one specific argument and do not care about the rest.

If you want all of the arguments to match, use any_await_with method instead.

Examples:

Below assertion passes because timer was awaited with positional argument 5. Keyword argument seconds is ignored.

>>> mocker(Teapot).mock("timer").match_args_any_await(5)
<chainmock._api.Assert object at ...>
>>> asyncio.run(Teapot().timer(5, seconds=15))

Below assertion passes because timer was awaited with keyword argument seconds=30. Positional argument is ignored.

>>> mocker(Teapot).mock("timer").match_args_any_await(seconds=30)
<chainmock._api.Assert object at ...>
>>> asyncio.run(Teapot().timer(1, seconds=30))

Parameters:

Name Type Description Default
*args Any

Expected positional arguments.

()
**kwargs Any

Expected keyword arguments.

{}

Returns:

Type Description
Assert

Assert instance so that calls can be chained.

match_args_any_call(self, *args, **kwargs)

Assert that any call has at least the specified arguments.

The assert passes if any call has at least the given positional or keyword arguments. This can be useful when you want to match just one specific argument and do not care about the rest.

If you want all of the arguments to match, use any_call_with method instead.

Examples:

Below assertion passes because add_tea was called with positional argument black. Keyword argument loose is ignored.

>>> mocker(Teapot).mock("add_tea").match_args_any_call("black")
<chainmock._api.Assert object at ...>
>>> Teapot().add_tea("black", loose=False)

Below assertion passes because add_tea was called with keyword argument loose=True. Positional argument is ignored.

>>> mocker(Teapot).mock("add_tea").match_args_any_call(loose=True)
<chainmock._api.Assert object at ...>
>>> Teapot().add_tea("oolong", loose=True)

Parameters:

Name Type Description Default
*args Any

Expected positional arguments.

()
**kwargs Any

Expected keyword arguments.

{}

Returns:

Type Description
Assert

Assert instance so that calls can be chained.

match_args_last_await(self, *args, **kwargs)

Assert that the most recent await has at least the specified arguments.

The assert passes if the last await has at least the given positional or keyword arguments. This can be useful when you want to match just one specific argument and do not care about the rest.

If you want all of the arguments to match, use awaited_last_with method instead.

Examples:

Below assertion passes because timer was awaited with positional argument 5. Keyword argument seconds is ignored.

>>> mocker(Teapot).mock("timer").match_args_any_await(5)
<chainmock._api.Assert object at ...>
>>> asyncio.run(Teapot().timer(5, seconds=15))

Below assertion passes because timer was awaited with keyword argument seconds=30. Positional argument is ignored.

>>> mocker(teapot).mock("timer").match_args_any_await(seconds=30)
<chainmock._api.Assert object at ...>
>>> asyncio.run(teapot.timer(1, seconds=30))

Parameters:

Name Type Description Default
*args Any

Expected positional arguments.

()
**kwargs Any

Expected keyword arguments.

{}

Returns:

Type Description
Assert

Assert instance so that calls can be chained.

match_args_last_call(self, *args, **kwargs)

Assert that the most recent call has at least the specified arguments.

The assert passes if the last call has at least the given positional or keyword arguments. This can be useful when you want to match just one specific argument and do not care about the rest.

If you want all of the arguments to match, use called_last_with method instead.

Examples:

Below assertion passes because add_tea was called with positional argument black. Keyword argument loose is ignored.

>>> mocker(Teapot).mock("add_tea").match_args_last_call("black")
<chainmock._api.Assert object at ...>
>>> Teapot().add_tea("black", loose=False)

Below assertion passes because add_tea was called with keyword argument loose=True. Positional argument is ignored.

>>> mocker(teapot).mock("add_tea").match_args_last_call(loose=True)
<chainmock._api.Assert object at ...>
>>> teapot.add_tea("oolong", loose=True)

Parameters:

Name Type Description Default
*args Any

Expected positional arguments.

()
**kwargs Any

Expected keyword arguments.

{}

Returns:

Type Description
Assert

Assert instance so that calls can be chained.

not_awaited(self)

Assert that the mock was never awaited.

Wrapper for unittest.mock.AsyncMock.assert_not_awaited.

For more details see: unittest.mock.AsyncMock.assert_not_awaited

Examples:

>>> mocker(Teapot).mock("timer").not_awaited()
<chainmock._api.Assert object at ...>

Returns:

Type Description
Assert

Assert instance so that calls can be chained.

not_called(self)

Assert that the mock was never called.

Wrapper for unittest.mock.Mock.assert_not_called.

For more details see: unittest.mock.Mock.assert_not_called

Examples:

>>> mocker(Teapot).mock("pour").not_called()
<chainmock._api.Assert object at ...>

Returns:

Type Description
Assert

Assert instance so that calls can be chained.

return_value(self, value)

Set the value that will be returned when the mocked attribute is called.

Wrapper for unittest.mock.Mock.return_value.

For more details see: unittest.mock.Mock.return_value

Examples:

Mock the return value of method brew:

>>> mocker(Teapot).mock("brew").return_value("mocked")
<chainmock._api.Assert object at ...>
>>> Teapot().brew()
'mocked'

Parameters:

Name Type Description Default
value Any

Return value to set to the mocked call.

required

Returns:

Type Description
Assert

Assert instance so that calls can be chained.

self(self)

Return the mock associated with this assertion.

Examples:

Use self to return mock and add more assertions:

>>> teapot = Teapot()
>>> mocked = mocker(teapot).mock("fill").called_once().self()
>>> mocked.mock("boil").called_once()
<chainmock._api.Assert object at ...>
>>> teapot.fill()
>>> teapot.boil()

Without self the above example can be written also like this:

>>> teapot = Teapot()
>>> mocked = mocker(teapot)
>>> mocked.mock("fill").called_once()
<chainmock._api.Assert object at ...>
>>> mocked.mock("boil").called_once()
<chainmock._api.Assert object at ...>
>>> teapot.fill()
>>> teapot.boil()

Returns:

Type Description
Mock

Mock instance associated with this assertion.

side_effect(self, value)

Set a side effect that will occur when the mocked attribute is called.

Side effect can be a function to call, an iterable or an exception (class or instance) to be raised. If you pass in a function it will be called with same arguments as the mock.

If you pass in an iterable, it is used to retrieve an iterator which must yield a value on every call. This value can either be an exception instance to be raised, or a value to be returned from the call to the mock.

Wrapper for unittest.mock.Mock.side_effect.

For more details see: unittest.mock.Mock.side_effect

Examples:

Raise an exception when the method brew is called:

>>> mocker(Teapot).mock("brew").side_effect(Exception("No tea!"))
<chainmock._api.Assert object at ...>
>>> Teapot().brew()
Traceback (most recent call last):
  ...
Exception: No tea!

Replace method fill with another function:

>>> mocker(teapot).mock("fill").side_effect(lambda x: x + 1)
<chainmock._api.Assert object at ...>
>>> teapot.fill(1)
2

Use a list to return a sequence of values:

>>> mocker(teapot).mock("pour").side_effect([2, 1, Exception("empty")])
<chainmock._api.Assert object at ...>
>>> teapot.pour()
2
>>> teapot.pour()
1
>>> teapot.pour()
Traceback (most recent call last):
  ...
Exception: empty

Parameters:

Name Type Description Default
value Any

Function to be called when the mock is called, an iterable or an exception (class or instance) to be raised.

required

Returns:

Type Description
Assert

Assert instance so that calls can be chained.