Skip to content

Commit 263b5c8

Browse files
committed
Use a dict to handle next scopes
1 parent 59fcc91 commit 263b5c8

File tree

3 files changed

+13
-14
lines changed

3 files changed

+13
-14
lines changed

src/_pytest/fixtures.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -451,7 +451,7 @@ def __init__(self, pyfuncitem, *, _ispytest: bool = False) -> None:
451451

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

457457
@property
@@ -1013,7 +1013,7 @@ def __init__(
10131013

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

10191019
def addfinalizer(self, finalizer: Callable[[], object]) -> None:

src/_pytest/scope.py

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ def index(self) -> int:
3333

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

3838
@classmethod
3939
def from_user(
@@ -61,19 +61,18 @@ def from_user(
6161
# Ordered list of scopes which can contain many tests (in practice all except Function).
6262
HIGH_SCOPES = [x for x in Scope if x is not Scope.Function]
6363

64+
# Maps a high-level scope to its next scope. Function is absent here because it
65+
# is the bottom-most scope.
66+
_NEXT_SCOPES = {
67+
Scope.Session: Scope.Package,
68+
Scope.Package: Scope.Module,
69+
Scope.Module: Scope.Class,
70+
Scope.Class: Scope.Function,
71+
}
72+
6473

6574
@lru_cache(maxsize=None)
6675
def _scope_to_index(scope: Scope) -> int:
6776
"""Implementation of Scope.index() as a free function so we can cache it."""
6877
scopes = list(Scope)
6978
return scopes.index(scope)
70-
71-
72-
@lru_cache(maxsize=None)
73-
def _next_scope(scope: Scope) -> Scope:
74-
"""Implementation of Scope.next() as a free function so we can cache it."""
75-
if scope is Scope.Function:
76-
raise ValueError("Function is the bottom scope")
77-
scopes = list(Scope)
78-
index = scopes.index(scope)
79-
return scopes[index + 1]

testing/test_scope.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ def test_next() -> None:
1818
assert Scope.Module.next() is Scope.Class
1919
assert Scope.Class.next() is Scope.Function
2020

21-
with pytest.raises(ValueError):
21+
with pytest.raises(KeyError):
2222
Scope.Function.next()
2323

2424

0 commit comments

Comments
 (0)