Skip to content

Asserters#

Asserters are the core of this module's business logic. They are the objects responsible for checking whether other objects fulfill a given expectation.

Each asserter must adhere to the following protocol:

Python
class AsserterProtocol(Protocol):
    """
    Asserter that checks whether the given expectation is fulfilled by an object.
    """

    expectation: Any
    asserter_factory: 'type[AsserterFactoryProtocol]'

    def __init__(
        self,
        asserter_factory: 'type[AsserterFactoryProtocol]',
        expectation: Any,
    ) -> None: ...

    @classmethod
    def matches(cls, expectation: Any) -> bool:
        """
        Determines whether the provided expectation can be handled by this asserter.

        :param expectation: the expectation to be tested
        """

    def assert_object(self, object_: Any) -> None:
        """
        Asserts whether the expectation is fulfilled by an object.

        :param object_: the object to be tested
        """

Asserter Factories#

When asserting objects, asserters are created from expectations using factories. The factory maintains an ordered sequence of asserter classes. When creating an asserter for a specific expectation, the factory iterates over the classes and uses the first one for which the matches method returns True.

The module provides a BuiltInAsserterFactory that includes all out-of-the-box asserters. Additionally, there is a blank factory called AsserterFactory that does not have any asserters registered.

To add an asserter to the factory, use the register_asserter class method with the following signature:

Python
1
2
3
4
5
6
def register_asserter(
    asserter: type[AsserterProtocol],
    *,
    after: type[AsserterProtocol] | None = None,
    before: type[AsserterProtocol] | None = None,
) -> None:

The asserter is registered at the earliest possible position. If after and before parameters are not set, it is added to the beginning of the list to be matched when creating an asserter for expectations. The after and before parameters allow you to specify constraints on the asserter's position.

When creating a subclass of a factory, it initially uses the same asserters collection as its base class. However, once the first asserter is registered, the collection from the base class is copied before adding new asserters.