Skip to content

Track exceptions when setting up and finalizing fixtures #12163

Closed as not planned
@ShurikMen

Description

@ShurikMen

There is a task to track exceptions when setting up and finalizing fixtures.
When setting up, an exception can be obtained in the pytest_fixture_setup hook:

@pytest.hookimpl(hookwrapper=True)
def pytest_fixture_setup(fixturedef):
    result = yield
    if result.exception:
        print('SETUP EXCEPTION in {0}: {1}'.format(fixturedef.argname, result.exception))

But at finalizing, you can't just get a list of exceptions of all finalizers that have been executed. Because there is no analog of the result as in the pytest_fixture_setup hook.
I propose to finalize the pytest_fixture_post_finalizer specification and an additional argument that will contain the exclusion(s) of all fixture finalizers.

src/_pytest/hookspec.py:

def pytest_fixture_post_finalizer(
    fixturedef: "FixtureDef[Any]", request: "SubRequest", exception: "BaseException | None"
) -> None:

src/_pytest/fixtures.py::FixtureDef::finish

        node = request.node
        if len(exceptions) == 1:
            final_exception = exceptions[0]
        elif len(exceptions) > 1:
            msg = f'errors while tearing down fixture "{self.argname}" of {node}'
            final_exception = BaseExceptionGroup(msg, exceptions[::-1])
        else:
            final_exception = None
        node.ihook.pytest_fixture_post_finalizer(fixturedef=self, request=request, exception=final_exception)
        # Even if finalization fails, we invalidate the cached fixture
        # value and remove all finalizers because they may be bound methods
        # which will keep instances alive.
        self.cached_result = None
        self._finalizers.clear()
        if final_exception:
            raise final_exception

Metadata

Metadata

Assignees

No one assigned

    Labels

    stalestatus: needs informationreporter needs to provide more information; can be closed after 2 or more weeks of inactivitytopic: fixturesanything involving fixtures directly or indirectlytype: proposalproposal for a new feature, often to gather opinions or design the API around the new feature

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions