Skip to content

Commit

Permalink
Use a dict to handle next scopes
Browse files Browse the repository at this point in the history
  • Loading branch information
nicoddemus committed Jul 23, 2021
1 parent 59fcc91 commit 263b5c8
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 14 deletions.
4 changes: 2 additions & 2 deletions src/_pytest/fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -451,7 +451,7 @@ def __init__(self, pyfuncitem, *, _ispytest: bool = False) -> None:

@property
def scope(self) -> "_ScopeName":
"""Backward-compatibility to return the scope string value."""
"""Scope string, one of "function", "class", "module", "package", "session"."""
return self._scope.value # type:ignore[return-value]

@property
Expand Down Expand Up @@ -1013,7 +1013,7 @@ def __init__(

@property
def scope(self) -> "_ScopeName":
"""Backward-compatibility to return the scope string value."""
"""Scope string, one of "function", "class", "module", "package", "session"."""
return self._scope.value # type:ignore[return-value]

def addfinalizer(self, finalizer: Callable[[], object]) -> None:
Expand Down
21 changes: 10 additions & 11 deletions src/_pytest/scope.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def index(self) -> int:

def next(self) -> "Scope":
"""Return the next scope (from top to bottom)."""
return _next_scope(self)
return _NEXT_SCOPES[self]

@classmethod
def from_user(
Expand Down Expand Up @@ -61,19 +61,18 @@ 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]

# Maps a high-level scope to its next scope. Function is absent here because it
# is the bottom-most scope.
_NEXT_SCOPES = {
Scope.Session: Scope.Package,
Scope.Package: Scope.Module,
Scope.Module: Scope.Class,
Scope.Class: Scope.Function,
}


@lru_cache(maxsize=None)
def _scope_to_index(scope: Scope) -> int:
"""Implementation of Scope.index() as a free function so we can cache it."""
scopes = list(Scope)
return scopes.index(scope)


@lru_cache(maxsize=None)
def _next_scope(scope: Scope) -> Scope:
"""Implementation of Scope.next() as a free function so we can cache it."""
if scope is Scope.Function:
raise ValueError("Function is the bottom scope")
scopes = list(Scope)
index = scopes.index(scope)
return scopes[index + 1]
2 changes: 1 addition & 1 deletion testing/test_scope.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def test_next() -> None:
assert Scope.Module.next() is Scope.Class
assert Scope.Class.next() is Scope.Function

with pytest.raises(ValueError):
with pytest.raises(KeyError):
Scope.Function.next()


Expand Down

0 comments on commit 263b5c8

Please sign in to comment.