Skip to content

Asserting Objects#

The module provides two ways of asserting objects.

Using the assert_object Function#

The most basic way to assert an object is by using the following function:

Python
1
2
3
4
5
6
def assert_object(
    expectation: Any,
    object_: Any,
    *,
    asserter_factory: type[AsserterFactoryProtocol] = BuiltInAsserterFactory,
) -> None: ...

In basic usage, it accepts an expectation and an object to be asserted. For more complicated use cases, it also accepts a custom asserter factory — a class used to create asserters that ensure a given type of expectation is fulfilled by the provided object.

The function doesn't return anything but raises an AssertionError with an error description as a message when the object does not fulfill the expectation.

For more information on asserters and factories, see Asserters.

Using the Expectation Class#

The module also provides an Expectation class, which overrides the __eq__ magic method to perform object assertion.

It is initialized with the expectation and optionally an asserter factory to be used. Then it can be compared to an object that should fulfill the expectation.

The comparison will return True if the object fulfills the expectation and False otherwise.

Python
assert Expectation(expectation) == object_
assert Expectation(expectation) != object_

This approach is mostly useful in combination with assert_context. The following code checks that the return value of foo() fulfills the expectation:

Python
with assert_context(result=Expectation(expectation)) as context:
    context.set(foo())