pytest_timeout.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. """Timeout for tests to stop hanging testruns
  2. This plugin will dump the stack and terminate the test. This can be
  3. useful when running tests on a continuous integration server.
  4. If the platform supports SIGALRM this is used to raise an exception in
  5. the test, otherwise os._exit(1) is used.
  6. """
  7. import os
  8. import signal
  9. import sys
  10. import threading
  11. import traceback
  12. from collections import namedtuple
  13. from distutils.version import StrictVersion
  14. import py
  15. import pytest
  16. HAVE_SIGALRM = hasattr(signal, 'SIGALRM')
  17. if HAVE_SIGALRM:
  18. DEFAULT_METHOD = 'signal'
  19. else:
  20. DEFAULT_METHOD = 'thread'
  21. TIMEOUT_DESC = """
  22. Timeout in seconds before dumping the stacks. Default is 0 which
  23. means no timeout.
  24. """.strip()
  25. METHOD_DESC = """
  26. Timeout mechanism to use. 'signal' uses SIGALRM if available,
  27. 'thread' uses a timer thread. The default is to use 'signal' and fall
  28. back to 'thread'.
  29. """.strip()
  30. FUNC_ONLY_DESC = """
  31. When set to True, defers the timeout evaluation to only the test
  32. function body, ignoring the time it takes when evaluating any fixtures
  33. used in the test.
  34. """.strip()
  35. Settings = namedtuple('Settings', ['timeout', 'method', 'func_only'])
  36. @pytest.hookimpl
  37. def pytest_addoption(parser):
  38. """Add options to control the timeout plugin"""
  39. group = parser.getgroup(
  40. 'timeout', 'Interrupt test run and dump stacks of all threads after '
  41. 'a test times out')
  42. group.addoption('--timeout',
  43. type=float,
  44. help=TIMEOUT_DESC)
  45. group.addoption('--timeout_method',
  46. action='store',
  47. choices=['signal', 'thread'],
  48. help='Deprecated, use --timeout-method')
  49. group.addoption('--timeout-method',
  50. dest='timeout_method',
  51. action='store',
  52. choices=['signal', 'thread'],
  53. help=METHOD_DESC)
  54. parser.addini('timeout', TIMEOUT_DESC)
  55. parser.addini('timeout_method', METHOD_DESC)
  56. parser.addini('timeout_func_only', FUNC_ONLY_DESC, type='bool')
  57. @pytest.hookimpl
  58. def pytest_configure(config):
  59. # Register the marker so it shows up in --markers output.
  60. config.addinivalue_line(
  61. 'markers',
  62. 'timeout(timeout, method=None, func_only=False): Set a timeout, timeout '
  63. 'method and func_only evaluation on just one test item. The first '
  64. 'argument, *timeout*, is the timeout in seconds while the keyword, '
  65. '*method*, takes the same values as the --timeout_method option. The '
  66. '*func_only* keyword, when set to True, defers the timeout evaluation '
  67. 'to only the test function body, ignoring the time it takes when '
  68. 'evaluating any fixrures used in the test.')
  69. settings = get_env_settings(config)
  70. config._env_timeout = settings.timeout
  71. config._env_timeout_method = settings.method
  72. config._env_timeout_func_only = settings.func_only
  73. @pytest.hookimpl(hookwrapper=True)
  74. def pytest_runtest_protocol(item):
  75. func_only = get_func_only_setting(item)
  76. if func_only is False:
  77. timeout_setup(item)
  78. outcome = yield
  79. if func_only is False:
  80. timeout_teardown(item)
  81. @pytest.hookimpl(hookwrapper=True)
  82. def pytest_runtest_call(item):
  83. func_only = get_func_only_setting(item)
  84. if func_only is True:
  85. timeout_setup(item)
  86. outcome = yield
  87. if func_only is True:
  88. timeout_teardown(item)
  89. @pytest.hookimpl(tryfirst=True)
  90. def pytest_report_header(config):
  91. if config._env_timeout:
  92. return ["timeout: %ss\ntimeout method: %s\ntimeout func_only: %s" %
  93. (config._env_timeout,
  94. config._env_timeout_method,
  95. config._env_timeout_func_only)]
  96. @pytest.hookimpl(tryfirst=True)
  97. def pytest_exception_interact(node):
  98. timeout_teardown(node)
  99. @pytest.hookimpl
  100. def pytest_enter_pdb():
  101. # Since pdb.set_trace happens outside of any pytest control, we don't have
  102. # any pytest ``item`` here, so we cannot use timeout_teardown. Thus, we
  103. # need another way to signify that the timeout should not be performed.
  104. global SUPPRESS_TIMEOUT
  105. SUPPRESS_TIMEOUT = True
  106. SUPPRESS_TIMEOUT = False
  107. def timeout_setup(item):
  108. """Setup up a timeout trigger and handler"""
  109. params = get_params(item)
  110. if params.timeout is None or params.timeout <= 0:
  111. return
  112. if params.method == 'signal':
  113. def handler(signum, frame):
  114. __tracebackhide__ = True
  115. timeout_sigalrm(item, params.timeout)
  116. def cancel():
  117. signal.setitimer(signal.ITIMER_REAL, 0)
  118. signal.signal(signal.SIGALRM, signal.SIG_DFL)
  119. item.cancel_timeout = cancel
  120. signal.signal(signal.SIGALRM, handler)
  121. signal.setitimer(signal.ITIMER_REAL, params.timeout)
  122. elif params.method == 'thread':
  123. timer = threading.Timer(params.timeout, timeout_timer,
  124. (item, params.timeout))
  125. def cancel():
  126. timer.cancel()
  127. timer.join()
  128. item.cancel_timeout = cancel
  129. timer.start()
  130. def timeout_teardown(item):
  131. """Cancel the timeout trigger if it was set"""
  132. # When skipping is raised from a pytest_runtest_setup function
  133. # (as is the case when using the pytest.mark.skipif marker) we
  134. # may be called without our setup counterpart having been
  135. # called.
  136. cancel = getattr(item, 'cancel_timeout', None)
  137. if cancel:
  138. cancel()
  139. def get_env_settings(config):
  140. timeout = config.getvalue('timeout')
  141. if timeout is None:
  142. timeout = _validate_timeout(
  143. os.environ.get('PYTEST_TIMEOUT'),
  144. 'PYTEST_TIMEOUT environment variable')
  145. if timeout is None:
  146. ini = config.getini('timeout')
  147. if ini:
  148. timeout = _validate_timeout(ini, 'config file')
  149. method = config.getvalue('timeout_method')
  150. if method is None:
  151. ini = config.getini('timeout_method')
  152. if ini:
  153. method = _validate_method(ini, 'config file')
  154. if method is None:
  155. method = DEFAULT_METHOD
  156. func_only = config.getini('timeout_func_only')
  157. if func_only == []:
  158. # No value set
  159. func_only = None
  160. if func_only is not None:
  161. func_only = _validate_func_only(func_only, 'config file')
  162. return Settings(timeout, method, func_only or False)
  163. def get_func_only_setting(item):
  164. """Return the func_only setting for an item"""
  165. func_only = None
  166. marker = item.get_closest_marker('timeout')
  167. if marker:
  168. settings = get_params(item, marker=marker)
  169. func_only = _validate_func_only(settings.func_only, 'marker')
  170. if func_only is None:
  171. func_only = item.config._env_timeout_func_only
  172. if func_only is None:
  173. func_only = False
  174. return func_only
  175. def get_params(item, marker=None):
  176. """Return (timeout, method) for an item"""
  177. timeout = method = func_only = None
  178. if not marker:
  179. marker = item.get_closest_marker('timeout')
  180. if marker is not None:
  181. settings = _parse_marker(item.get_closest_marker(name='timeout'))
  182. timeout = _validate_timeout(settings.timeout, 'marker')
  183. method = _validate_method(settings.method, 'marker')
  184. func_only = _validate_func_only(settings.func_only, 'marker')
  185. if timeout is None:
  186. timeout = item.config._env_timeout
  187. if method is None:
  188. method = item.config._env_timeout_method
  189. if func_only is None:
  190. func_only = item.config._env_timeout_func_only
  191. return Settings(timeout, method, func_only)
  192. def _parse_marker(marker):
  193. """Return (timeout, method) tuple from marker
  194. Either could be None. The values are not interpreted, so
  195. could still be bogus and even the wrong type.
  196. """
  197. if not marker.args and not marker.kwargs:
  198. raise TypeError('Timeout marker must have at least one argument')
  199. timeout = method = func_only = NOTSET = object()
  200. for kw, val in marker.kwargs.items():
  201. if kw == 'timeout':
  202. timeout = val
  203. elif kw == 'method':
  204. method = val
  205. elif kw == 'func_only':
  206. func_only = val
  207. else:
  208. raise TypeError(
  209. 'Invalid keyword argument for timeout marker: %s' % kw)
  210. if len(marker.args) >= 1 and timeout is not NOTSET:
  211. raise TypeError(
  212. 'Multiple values for timeout argument of timeout marker')
  213. elif len(marker.args) >= 1:
  214. timeout = marker.args[0]
  215. if len(marker.args) >= 2 and method is not NOTSET:
  216. raise TypeError(
  217. 'Multiple values for method argument of timeout marker')
  218. elif len(marker.args) >= 2:
  219. method = marker.args[1]
  220. if len(marker.args) > 2:
  221. raise TypeError('Too many arguments for timeout marker')
  222. if timeout is NOTSET:
  223. timeout = None
  224. if method is NOTSET:
  225. method = None
  226. if func_only is NOTSET:
  227. func_only = None
  228. return Settings(timeout, method, func_only)
  229. def _validate_timeout(timeout, where):
  230. """Helper for get_params()"""
  231. if timeout is None:
  232. return None
  233. try:
  234. return float(timeout)
  235. except ValueError:
  236. raise ValueError('Invalid timeout %s from %s' % (timeout, where))
  237. def _validate_method(method, where):
  238. """Helper for get_params()"""
  239. if method is None:
  240. return None
  241. if method not in ['signal', 'thread']:
  242. raise ValueError('Invalid method %s from %s' % (method, where))
  243. return method
  244. def _validate_func_only(func_only, where):
  245. """Helper for get_params()"""
  246. if func_only is None:
  247. return False
  248. if not isinstance(func_only, bool):
  249. raise ValueError('Invalid func_only value %s from %s' % (func_only, where))
  250. return func_only
  251. def timeout_sigalrm(item, timeout):
  252. """Dump stack of threads and raise an exception
  253. This will output the stacks of any threads other then the
  254. current to stderr and then raise an AssertionError, thus
  255. terminating the test.
  256. """
  257. if SUPPRESS_TIMEOUT:
  258. return
  259. __tracebackhide__ = True
  260. nthreads = len(threading.enumerate())
  261. if nthreads > 1:
  262. write_title('Timeout', sep='+')
  263. dump_stacks()
  264. if nthreads > 1:
  265. write_title('Timeout', sep='+')
  266. pytest.fail('Timeout >%ss' % timeout)
  267. def timeout_timer(item, timeout):
  268. """Dump stack of threads and call os._exit()
  269. This disables the capturemanager and dumps stdout and stderr.
  270. Then the stacks are dumped and os._exit(1) is called.
  271. """
  272. if SUPPRESS_TIMEOUT:
  273. return
  274. try:
  275. capman = item.config.pluginmanager.getplugin('capturemanager')
  276. if capman:
  277. pytest_version = StrictVersion(pytest.__version__)
  278. if pytest_version >= StrictVersion('3.7.3'):
  279. capman.suspend_global_capture(item)
  280. stdout, stderr = capman.read_global_capture()
  281. else:
  282. stdout, stderr = capman.suspend_global_capture(item)
  283. else:
  284. stdout, stderr = None, None
  285. write_title('Timeout', sep='+')
  286. caplog = item.config.pluginmanager.getplugin('_capturelog')
  287. if caplog and hasattr(item, 'capturelog_handler'):
  288. log = item.capturelog_handler.stream.getvalue()
  289. if log:
  290. write_title('Captured log')
  291. write(log)
  292. if stdout:
  293. write_title('Captured stdout')
  294. write(stdout)
  295. if stderr:
  296. write_title('Captured stderr')
  297. write(stderr)
  298. dump_stacks()
  299. write_title('Timeout', sep='+')
  300. except Exception:
  301. traceback.print_exc()
  302. finally:
  303. sys.stdout.flush()
  304. sys.stderr.flush()
  305. os._exit(1)
  306. def dump_stacks():
  307. """Dump the stacks of all threads except the current thread"""
  308. current_ident = threading.current_thread().ident
  309. for thread_ident, frame in sys._current_frames().items():
  310. if thread_ident == current_ident:
  311. continue
  312. for t in threading.enumerate():
  313. if t.ident == thread_ident:
  314. thread_name = t.name
  315. break
  316. else:
  317. thread_name = '<unknown>'
  318. write_title('Stack of %s (%s)' % (thread_name, thread_ident))
  319. write(''.join(traceback.format_stack(frame)))
  320. def write_title(title, stream=None, sep='~'):
  321. """Write a section title
  322. If *stream* is None sys.stderr will be used, *sep* is used to
  323. draw the line.
  324. """
  325. if stream is None:
  326. stream = sys.stderr
  327. width = py.io.get_terminal_width()
  328. fill = int((width - len(title) - 2) / 2)
  329. line = ' '.join([sep * fill, title, sep * fill])
  330. if len(line) < width:
  331. line += sep * (width - len(line))
  332. stream.write('\n' + line + '\n')
  333. def write(text, stream=None):
  334. """Write text to stream
  335. Pretty stupid really, only here for symetry with .write_title().
  336. """
  337. if stream is None:
  338. stream = sys.stderr
  339. stream.write(text)