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