scope.py 2.8 KB

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