Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

no cache fixtures POC #12816

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 26 additions & 6 deletions src/_pytest/fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@
def get_scope_node(node: nodes.Node, scope: Scope) -> nodes.Node | None:
import _pytest.python

if scope is Scope.Function:
if scope is Scope.Function or scope is Scope.Invocation:
# Type ignored because this is actually safe, see:
# https://github.com/python/mypy/issues/4717
return node.getparent(nodes.Item) # type: ignore[type-abstract]
Expand Down Expand Up @@ -185,7 +185,7 @@
) -> Iterator[FixtureArgKey]:
"""Return list of keys for all parametrized arguments which match
the specified scope."""
assert scope is not Scope.Function
assert scope in HIGH_SCOPES

try:
callspec: CallSpec2 = item.callspec # type: ignore[attr-defined]
Expand Down Expand Up @@ -534,6 +534,14 @@
f'The fixture value for "{argname}" is not available. '
"This can happen when the fixture has already been torn down."
)

if (
isinstance(fixturedef, FixtureDef)
and fixturedef is not None
and fixturedef.scope == Scope.Invocation.value
):
self._fixture_defs.pop(argname)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

as mentioned in the issue before, i think its important to use a scope name here as indicator instead of the new boolean (in particular as use_cache as implemented here invalidates the scope

the scope name we had in mind back in 2020 was "invocation" to mean that the scope of a validity for a fixture value would be the call (be it other fixture or test function in which it was used

i like the hack with just popping the values as a workaround for the current tech debt as it seems like the impact is limited, but i'd like the input of the others in this

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see.
If we insist on going with the scope like approach rather than the boolean, I think we could still work-around this while leaving the implementation the same. We just change the arg name to a string scope and will currently only support one scope for this (or two considering default behavior).
This way changing the implementation to a more robust infrastructure centered around the actual scoping won't be breaking.
I think this would be a step in the right direction and would probably solve the general use-case for this issue :)
Thoughts?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's the rough idea - add a new scope name, then use the workaround you created and gate on the scope name

For good measure we might need a test that ensures setup/teardown is in sync with the usage sites

Copy link
Author

@niroshaimos niroshaimos Oct 5, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've made the rough changes as I understand the request.
I have added a new scope Invocation which will be a scope lower than Function (of course it's cleanup scope will occur during Function cleanup level)
Of course if this is the direction we will be going with I'll move the tests to test_scope.py
When it comes to coverage of the feature, I believe what I have created should be sufficient. I am not sure I understand the additional test suggestions you have provided. If you could expand on it, that would be great.
Please take a look and tell me what you think :)


return fixturedef.cached_result[0]

def _iter_chain(self) -> Iterator[SubRequest]:
Expand Down Expand Up @@ -614,9 +622,18 @@
)

# Make sure the fixture value is cached, running it if it isn't
fixturedef.execute(request=subrequest)
try:
fixturedef.execute(request=subrequest)
self._fixture_defs[argname] = fixturedef
finally:
for arg_name in fixturedef.argnames:
arg_fixture = self._fixture_defs.get(arg_name)
if (
arg_fixture is not None
and arg_fixture.scope == Scope.Invocation.value
):
self._fixture_defs.pop(arg_name)

Check warning on line 635 in src/_pytest/fixtures.py

View check run for this annotation

Codecov / codecov/patch

src/_pytest/fixtures.py#L635

Added line #L635 was not covered by tests

self._fixture_defs[argname] = fixturedef
return fixturedef

def _check_fixturedef_without_param(self, fixturedef: FixtureDef[object]) -> None:
Expand Down Expand Up @@ -757,7 +774,10 @@
requested_fixturedef: FixtureDef[object] | PseudoFixtureDef[object],
requested_scope: Scope,
) -> None:
if isinstance(requested_fixturedef, PseudoFixtureDef):
if (
isinstance(requested_fixturedef, PseudoFixtureDef)
or requested_scope == Scope.Invocation
):
return
if self._scope > requested_scope:
# Try to report something helpful.
Expand Down Expand Up @@ -1054,7 +1074,7 @@
requested_fixtures_that_should_finalize_us.append(fixturedef)

# Check for (and return) cached value/exception.
if self.cached_result is not None:
if self.cached_result is not None and self.scope != Scope.Invocation.value:
request_cache_key = self.cache_key(request)
cache_key = self.cached_result[1]
try:
Expand Down
7 changes: 5 additions & 2 deletions src/_pytest/scope.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from typing import Literal


_ScopeName = Literal["session", "package", "module", "class", "function"]
_ScopeName = Literal["session", "package", "module", "class", "function", "invocation"]


@total_ordering
Expand All @@ -33,6 +33,7 @@ class Scope(Enum):
"""

# Scopes need to be listed from lower to higher.
Invocation: _ScopeName = "invocation"
Function: _ScopeName = "function"
Class: _ScopeName = "class"
Module: _ScopeName = "module"
Expand Down Expand Up @@ -88,4 +89,6 @@ def from_user(


# Ordered list of scopes which can contain many tests (in practice all except Function).
HIGH_SCOPES = [x for x in Scope if x is not Scope.Function]
HIGH_SCOPES = [
x for x in Scope if x is not Scope.Function and x is not Scope.Invocation
]
124 changes: 124 additions & 0 deletions testing/test_no_cache.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
from __future__ import annotations

from _pytest.pytester import Pytester


def test_setup_teardown_executed_for_every_fixture_usage_without_caching(
pytester: Pytester,
) -> None:
pytester.makepyfile(
"""
import pytest
import logging

@pytest.fixture(scope="invocation")
def fixt():
logging.info("&&Setting up fixt&&")
yield
logging.info("&&Tearing down fixt&&")


@pytest.fixture()
def a(fixt):
...


@pytest.fixture()
def b(fixt):
...


def test(a, b, fixt):
assert False
"""
)

result = pytester.runpytest("--log-level=INFO")
assert result.ret == 1
result.stdout.fnmatch_lines(
[
*["*&&Setting up fixt&&*"] * 3,
*["*&&Tearing down fixt&&*"] * 3,
]
)


def test_setup_teardown_executed_for_every_getfixturevalue_usage_without_caching(
pytester: Pytester,
) -> None:
pytester.makepyfile(
"""
import pytest
import logging

@pytest.fixture(scope="invocation")
def fixt():
logging.info("&&Setting up fixt&&")
yield
logging.info("&&Tearing down fixt&&")


def test(request):
random_nums = [request.getfixturevalue('fixt') for _ in range(3)]
assert False
"""
)
result = pytester.runpytest("--log-level=INFO")
assert result.ret == 1
result.stdout.fnmatch_lines(
[
*["*&&Setting up fixt&&*"] * 3,
*["*&&Tearing down fixt&&*"] * 3,
]
)


def test_non_cached_fixture_generates_unique_values_per_usage(
pytester: Pytester,
) -> None:
pytester.makepyfile(
"""
import pytest

@pytest.fixture(scope="invocation")
def random_num():
import random
return random.randint(-100_000_000_000, 100_000_000_000)


@pytest.fixture()
def a(random_num):
return random_num


@pytest.fixture()
def b(random_num):
return random_num


def test(a, b, random_num):
assert a != b != random_num
"""
)
pytester.runpytest().assert_outcomes(passed=1)


def test_non_cached_fixture_generates_unique_values_per_getfixturevalue_usage(
pytester: Pytester,
) -> None:
pytester.makepyfile(
"""
import pytest

@pytest.fixture(scope="invocation")
def random_num():
import random
yield random.randint(-100_000_000_000, 100_000_000_000)


def test(request):
random_nums = [request.getfixturevalue('random_num') for _ in range(3)]
assert random_nums[0] != random_nums[1] != random_nums[2]
"""
)
pytester.runpytest().assert_outcomes(passed=1)
5 changes: 3 additions & 2 deletions testing/test_scope.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,10 @@ def test_next_lower() -> None:
assert Scope.Package.next_lower() is Scope.Module
assert Scope.Module.next_lower() is Scope.Class
assert Scope.Class.next_lower() is Scope.Function
assert Scope.Function.next_lower() is Scope.Invocation

with pytest.raises(ValueError, match="Function is the lower-most scope"):
Scope.Function.next_lower()
with pytest.raises(ValueError, match="Invocation is the lower-most scope"):
Scope.Invocation.next_lower()


def test_next_higher() -> None:
Expand Down
Loading