def test_scoped_fixture_caching_exception(pytester: Pytester) -> None:
    """Make sure setup & finalization is only run once for scoped fixture, with a cached exception."""
    pytester.makepyfile(
        """
        from __future__ import annotations

        import pytest
        executed_crash: list[str] = []


        @pytest.fixture(scope="class")
        def fixture_crash(request: pytest.FixtureRequest) -> None:
            executed_crash.append("fix_crash setup")

            def my_finalizer() -> None:
                executed_crash.append("fix_crash teardown")

            request.addfinalizer(my_finalizer)

            raise Exception("foo")


        class TestFixtureCachingException:
            @pytest.mark.xfail
            def test_crash_1(self, fixture_crash: None) -> None:
                ...

            @pytest.mark.xfail
            def test_crash_2(self, fixture_crash: None) -> None:
                ...


        def test_crash_expected_setup_and_teardown() -> None:
            assert executed_crash == ["fix_crash setup", "fix_crash teardown"]
        """
    )
    result = pytester.runpytest()
    assert result.ret == 0
Make sure setup & finalization is only run once for scoped fixture, with a cached exception.
testing/python/fixtures.py