warnings.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. import sys
  2. import warnings
  3. from contextlib import contextmanager
  4. from typing import Generator
  5. from typing import Optional
  6. from typing import TYPE_CHECKING
  7. import pytest
  8. from _pytest.config import apply_warning_filters
  9. from _pytest.config import Config
  10. from _pytest.config import parse_warning_filter
  11. from _pytest.main import Session
  12. from _pytest.nodes import Item
  13. from _pytest.terminal import TerminalReporter
  14. if TYPE_CHECKING:
  15. from typing_extensions import Literal
  16. def pytest_configure(config: Config) -> None:
  17. config.addinivalue_line(
  18. "markers",
  19. "filterwarnings(warning): add a warning filter to the given test. "
  20. "see https://docs.pytest.org/en/stable/how-to/capture-warnings.html#pytest-mark-filterwarnings ",
  21. )
  22. @contextmanager
  23. def catch_warnings_for_item(
  24. config: Config,
  25. ihook,
  26. when: "Literal['config', 'collect', 'runtest']",
  27. item: Optional[Item],
  28. ) -> Generator[None, None, None]:
  29. """Context manager that catches warnings generated in the contained execution block.
  30. ``item`` can be None if we are not in the context of an item execution.
  31. Each warning captured triggers the ``pytest_warning_recorded`` hook.
  32. """
  33. config_filters = config.getini("filterwarnings")
  34. cmdline_filters = config.known_args_namespace.pythonwarnings or []
  35. with warnings.catch_warnings(record=True) as log:
  36. # mypy can't infer that record=True means log is not None; help it.
  37. assert log is not None
  38. if not sys.warnoptions:
  39. # If user is not explicitly configuring warning filters, show deprecation warnings by default (#2908).
  40. warnings.filterwarnings("always", category=DeprecationWarning)
  41. warnings.filterwarnings("always", category=PendingDeprecationWarning)
  42. warnings.filterwarnings("error", category=pytest.PytestRemovedIn7Warning)
  43. apply_warning_filters(config_filters, cmdline_filters)
  44. # apply filters from "filterwarnings" marks
  45. nodeid = "" if item is None else item.nodeid
  46. if item is not None:
  47. for mark in item.iter_markers(name="filterwarnings"):
  48. for arg in mark.args:
  49. warnings.filterwarnings(*parse_warning_filter(arg, escape=False))
  50. yield
  51. for warning_message in log:
  52. ihook.pytest_warning_captured.call_historic(
  53. kwargs=dict(
  54. warning_message=warning_message,
  55. when=when,
  56. item=item,
  57. location=None,
  58. )
  59. )
  60. ihook.pytest_warning_recorded.call_historic(
  61. kwargs=dict(
  62. warning_message=warning_message,
  63. nodeid=nodeid,
  64. when=when,
  65. location=None,
  66. )
  67. )
  68. def warning_record_to_str(warning_message: warnings.WarningMessage) -> str:
  69. """Convert a warnings.WarningMessage to a string."""
  70. warn_msg = warning_message.message
  71. msg = warnings.formatwarning(
  72. str(warn_msg),
  73. warning_message.category,
  74. warning_message.filename,
  75. warning_message.lineno,
  76. warning_message.line,
  77. )
  78. return msg
  79. @pytest.hookimpl(hookwrapper=True, tryfirst=True)
  80. def pytest_runtest_protocol(item: Item) -> Generator[None, None, None]:
  81. with catch_warnings_for_item(
  82. config=item.config, ihook=item.ihook, when="runtest", item=item
  83. ):
  84. yield
  85. @pytest.hookimpl(hookwrapper=True, tryfirst=True)
  86. def pytest_collection(session: Session) -> Generator[None, None, None]:
  87. config = session.config
  88. with catch_warnings_for_item(
  89. config=config, ihook=config.hook, when="collect", item=None
  90. ):
  91. yield
  92. @pytest.hookimpl(hookwrapper=True)
  93. def pytest_terminal_summary(
  94. terminalreporter: TerminalReporter,
  95. ) -> Generator[None, None, None]:
  96. config = terminalreporter.config
  97. with catch_warnings_for_item(
  98. config=config, ihook=config.hook, when="config", item=None
  99. ):
  100. yield
  101. @pytest.hookimpl(hookwrapper=True)
  102. def pytest_sessionfinish(session: Session) -> Generator[None, None, None]:
  103. config = session.config
  104. with catch_warnings_for_item(
  105. config=config, ihook=config.hook, when="config", item=None
  106. ):
  107. yield
  108. @pytest.hookimpl(hookwrapper=True)
  109. def pytest_load_initial_conftests(
  110. early_config: "Config",
  111. ) -> Generator[None, None, None]:
  112. with catch_warnings_for_item(
  113. config=early_config, ihook=early_config.hook, when="config", item=None
  114. ):
  115. yield