[Python] How do I run clean up functions even when a setup fixture fails? [duplicate]

Discussão em 'Python' iniciado por Stack, Julho 3, 2025.

  1. Stack

    Stack Membro Participativo

    I have some setup fixtures that need to run successfully before the test, like here. While doing my best to have them stable, they sometimes have errors on other machines, e.g. in a CI/CD pipeline. In that case I would like to run a teardown fixture to clean up the mess. For example, collect some information on the cause of the error and try to restore the environment into a defined state.

    Running below code with pytest -rP, I see "teardown", printed when setup succeeds and test_something fails. When I add the assert False in setup to fail the test, "teardown" is not printed any more.

    #!/usr/bin/env python3

    import pytest

    @pytest.fixture(autouse=True)
    def setup():
    print("setup")
    assert True
    # assert False

    @pytest.fixture(autouse=True)
    def teardown():
    yield
    print("teardown")

    def test_something():
    assert False


    Pytest docs write that this is expected:


    If an earlier fixture has a problem, though, and raises an exception, pytest will stop executing fixtures for that test and mark the test as having an error
    ​

    How can I run a clean up function that runs even when a setup fixture fails?

    Continue reading...

Compartilhe esta Página