Skip to content

Commit c203f16

Browse files
authored
Merge pull request #12121 from jakkdl/test_scope_fixture_caching
Add tests to ensure setup&finalization for scoped fixtures only run once.
2 parents 2e5da5d + bec0e9c commit c203f16

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

testing/python/fixtures.py

+74
Original file line numberDiff line numberDiff line change
@@ -4622,3 +4622,77 @@ def test_2(cls, request):
46224622
result = pytester.runpytest()
46234623
assert result.ret == ExitCode.OK
46244624
result.assert_outcomes(passed=3)
4625+
4626+
4627+
def test_scoped_fixture_caching(pytester: Pytester) -> None:
4628+
"""Make sure setup and finalization is only run once when using scoped fixture
4629+
multiple times."""
4630+
pytester.makepyfile(
4631+
"""
4632+
from __future__ import annotations
4633+
4634+
from typing import Generator
4635+
4636+
import pytest
4637+
executed: list[str] = []
4638+
@pytest.fixture(scope="class")
4639+
def fixture_1() -> Generator[None, None, None]:
4640+
executed.append("fix setup")
4641+
yield
4642+
executed.append("fix teardown")
4643+
4644+
4645+
class TestFixtureCaching:
4646+
def test_1(self, fixture_1: None) -> None:
4647+
assert executed == ["fix setup"]
4648+
4649+
def test_2(self, fixture_1: None) -> None:
4650+
assert executed == ["fix setup"]
4651+
4652+
4653+
def test_expected_setup_and_teardown() -> None:
4654+
assert executed == ["fix setup", "fix teardown"]
4655+
"""
4656+
)
4657+
result = pytester.runpytest()
4658+
assert result.ret == 0
4659+
4660+
4661+
def test_scoped_fixture_caching_exception(pytester: Pytester) -> None:
4662+
"""Make sure setup & finalization is only run once for scoped fixture, with a cached exception."""
4663+
pytester.makepyfile(
4664+
"""
4665+
from __future__ import annotations
4666+
4667+
import pytest
4668+
executed_crash: list[str] = []
4669+
4670+
4671+
@pytest.fixture(scope="class")
4672+
def fixture_crash(request: pytest.FixtureRequest) -> None:
4673+
executed_crash.append("fix_crash setup")
4674+
4675+
def my_finalizer() -> None:
4676+
executed_crash.append("fix_crash teardown")
4677+
4678+
request.addfinalizer(my_finalizer)
4679+
4680+
raise Exception("foo")
4681+
4682+
4683+
class TestFixtureCachingException:
4684+
@pytest.mark.xfail
4685+
def test_crash_1(self, fixture_crash: None) -> None:
4686+
...
4687+
4688+
@pytest.mark.xfail
4689+
def test_crash_2(self, fixture_crash: None) -> None:
4690+
...
4691+
4692+
4693+
def test_crash_expected_setup_and_teardown() -> None:
4694+
assert executed_crash == ["fix_crash setup", "fix_crash teardown"]
4695+
"""
4696+
)
4697+
result = pytester.runpytest()
4698+
assert result.ret == 0

0 commit comments

Comments
 (0)