faulthandler.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. from __future__ import annotations
  2. from collections.abc import Generator
  3. import os
  4. import sys
  5. from _pytest.config import Config
  6. from _pytest.config.argparsing import Parser
  7. from _pytest.nodes import Item
  8. from _pytest.stash import StashKey
  9. import pytest
  10. fault_handler_original_stderr_fd_key = StashKey[int]()
  11. fault_handler_stderr_fd_key = StashKey[int]()
  12. def pytest_addoption(parser: Parser) -> None:
  13. help = (
  14. "Dump the traceback of all threads if a test takes "
  15. "more than TIMEOUT seconds to finish"
  16. )
  17. parser.addini("faulthandler_timeout", help, default=0.0)
  18. def pytest_configure(config: Config) -> None:
  19. import faulthandler
  20. # at teardown we want to restore the original faulthandler fileno
  21. # but faulthandler has no api to return the original fileno
  22. # so here we stash the stderr fileno to be used at teardown
  23. # sys.stderr and sys.__stderr__ may be closed or patched during the session
  24. # so we can't rely on their values being good at that point (#11572).
  25. stderr_fileno = get_stderr_fileno()
  26. if faulthandler.is_enabled():
  27. config.stash[fault_handler_original_stderr_fd_key] = stderr_fileno
  28. config.stash[fault_handler_stderr_fd_key] = os.dup(stderr_fileno)
  29. faulthandler.enable(file=config.stash[fault_handler_stderr_fd_key])
  30. def pytest_unconfigure(config: Config) -> None:
  31. import faulthandler
  32. faulthandler.disable()
  33. # Close the dup file installed during pytest_configure.
  34. if fault_handler_stderr_fd_key in config.stash:
  35. os.close(config.stash[fault_handler_stderr_fd_key])
  36. del config.stash[fault_handler_stderr_fd_key]
  37. # Re-enable the faulthandler if it was originally enabled.
  38. if fault_handler_original_stderr_fd_key in config.stash:
  39. faulthandler.enable(config.stash[fault_handler_original_stderr_fd_key])
  40. del config.stash[fault_handler_original_stderr_fd_key]
  41. def get_stderr_fileno() -> int:
  42. try:
  43. fileno = sys.stderr.fileno()
  44. # The Twisted Logger will return an invalid file descriptor since it is not backed
  45. # by an FD. So, let's also forward this to the same code path as with pytest-xdist.
  46. if fileno == -1:
  47. raise AttributeError()
  48. return fileno
  49. except (AttributeError, ValueError):
  50. # pytest-xdist monkeypatches sys.stderr with an object that is not an actual file.
  51. # https://docs.python.org/3/library/faulthandler.html#issue-with-file-descriptors
  52. # This is potentially dangerous, but the best we can do.
  53. assert sys.__stderr__ is not None
  54. return sys.__stderr__.fileno()
  55. def get_timeout_config_value(config: Config) -> float:
  56. return float(config.getini("faulthandler_timeout") or 0.0)
  57. @pytest.hookimpl(wrapper=True, trylast=True)
  58. def pytest_runtest_protocol(item: Item) -> Generator[None, object, object]:
  59. timeout = get_timeout_config_value(item.config)
  60. if timeout > 0:
  61. import faulthandler
  62. stderr = item.config.stash[fault_handler_stderr_fd_key]
  63. faulthandler.dump_traceback_later(timeout, file=stderr)
  64. try:
  65. return (yield)
  66. finally:
  67. faulthandler.cancel_dump_traceback_later()
  68. else:
  69. return (yield)
  70. @pytest.hookimpl(tryfirst=True)
  71. def pytest_enter_pdb() -> None:
  72. """Cancel any traceback dumping due to timeout before entering pdb."""
  73. import faulthandler
  74. faulthandler.cancel_dump_traceback_later()
  75. @pytest.hookimpl(tryfirst=True)
  76. def pytest_exception_interact() -> None:
  77. """Cancel any traceback dumping due to an interactive exception being
  78. raised."""
  79. import faulthandler
  80. faulthandler.cancel_dump_traceback_later()