Debian Codegraph @

testing/web-platform/tests/tools/third_party/pytest/src/_pytest/scope.py

raw
1 """
2 Scope definition and related utilities.
3
4 Those are defined here, instead of in the 'fixtures' module because
5 their use is spread across many other pytest modules, and centralizing it in 'fixtures'
6 would cause circular references.
7
8 Also this makes the module light to import, as it should.
9 """
10
11 from enum import Enum
12 from functools import total_ordering
13 from typing import Literal
14 from typing import Optional
15
16
17 _ScopeName = Literal["session", "package", "module", "class", "function"]
18
19
20 @total_ordering
21 class Scope(Enum):
22 """
23 Represents one of the possible fixture scopes in pytest.
24
25 Scopes are ordered from lower to higher, that is:
26
27 ->>> higher ->>>
28
29 Function < Class < Module < Package < Session
30
31 <<<- lower <<<-
32 """
33
34 # Scopes need to be listed from lower to higher.
35 Function: _ScopeName = "function"
36 Class: _ScopeName = "class"
37 Module: _ScopeName = "module"
38 Package: _ScopeName = "package"
39 Session: _ScopeName = "session"
40
41 def next_lower(self) -> "Scope":
42 """Return the next lower scope."""
43 index = _SCOPE_INDICES[self]
44 if index == 0:
45 raise ValueError(f"{self} is the lower-most scope")
46 return _ALL_SCOPES[index - 1]
47
48 def next_higher(self) -> "Scope":
49 """Return the next higher scope."""
50 index = _SCOPE_INDICES[self]
51 if index == len(_SCOPE_INDICES) - 1:
52 raise ValueError(f"{self} is the upper-most scope")
53 return _ALL_SCOPES[index + 1]
54
55 def __lt__(self, other: "Scope") -> bool:
56 self_index = _SCOPE_INDICES[self]
57 other_index = _SCOPE_INDICES[other]
58 return self_index < other_index
59
60 @classmethod
61 def from_user(
62 cls, scope_name: _ScopeName, descr: str, where: Optional[str] = None
63 ) -> "Scope":
64 """
65 Given a scope name from the user, return the equivalent Scope enum. Should be used
66 whenever we want to convert a user provided scope name to its enum object.
67
68 If the scope name is invalid, construct a user friendly message and call pytest.fail.
69 """
70 from _pytest.outcomes import fail
71
72 try:
73 # Holding this reference is necessary for mypy at the moment.
74 scope = Scope(scope_name)
75 except ValueError:
76 fail(
77 "{} {}got an unexpected scope value '{}'".format(
78 descr, f"from {where} " if where else "", scope_name
79 ),
80 pytrace=False,
81 )
82 return scope
83
84
85 _ALL_SCOPES = list(Scope)
86 _SCOPE_INDICES = {scope: index for index, scope in enumerate(_ALL_SCOPES)}
87
88
89 # Ordered list of scopes which can contain many tests (in practice all except Function).
90 HIGH_SCOPES = [x for x in Scope if x is not Scope.Function]