Skip to content

Commit

Permalink
Merge pull request pytest-dev#12121 from jakkdl/test_scope_fixture_ca…
Browse files Browse the repository at this point in the history
…ching

Add tests to ensure setup&finalization for scoped fixtures only run once.
  • Loading branch information
bluetech authored Mar 16, 2024
2 parents 2e5da5d + bec0e9c commit c203f16
Showing 1 changed file with 74 additions and 0 deletions.
74 changes: 74 additions & 0 deletions testing/python/fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -4622,3 +4622,77 @@ def test_2(cls, request):
result = pytester.runpytest()
assert result.ret == ExitCode.OK
result.assert_outcomes(passed=3)


def test_scoped_fixture_caching(pytester: Pytester) -> None:
"""Make sure setup and finalization is only run once when using scoped fixture
multiple times."""
pytester.makepyfile(
"""
from __future__ import annotations
from typing import Generator
import pytest
executed: list[str] = []
@pytest.fixture(scope="class")
def fixture_1() -> Generator[None, None, None]:
executed.append("fix setup")
yield
executed.append("fix teardown")
class TestFixtureCaching:
def test_1(self, fixture_1: None) -> None:
assert executed == ["fix setup"]
def test_2(self, fixture_1: None) -> None:
assert executed == ["fix setup"]
def test_expected_setup_and_teardown() -> None:
assert executed == ["fix setup", "fix teardown"]
"""
)
result = pytester.runpytest()
assert result.ret == 0


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

0 comments on commit c203f16

Please sign in to comment.