| 1 |
import _thread |
| 2 |
import contextlib |
| 3 |
import functools |
| 4 |
import sys |
| 5 |
import threading |
| 6 |
import time |
| 7 |
import unittest |
| 8 |
|
| 9 |
from test import support |
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
def threading_setup(): |
| 25 |
return _thread._count(), len(threading._dangling) |
| 26 |
|
| 27 |
|
| 28 |
def threading_cleanup(*original_values): |
| 29 |
orig_count, orig_ndangling = original_values |
| 30 |
support.gc_collect() |
| 31 |
|
| 32 |
timeout = 1.0 |
| 33 |
for _ in support.sleeping_retry(timeout, error=False): |
| 34 |
|
| 35 |
|
| 36 |
dangling_threads = list(threading._dangling) |
| 37 |
count = _thread._count() |
| 38 |
|
| 39 |
if count <= orig_count: |
| 40 |
return |
| 41 |
|
| 42 |
|
| 43 |
support.environment_altered = True |
| 44 |
support.print_warning( |
| 45 |
f"threading_cleanup() failed to clean up threads " |
| 46 |
f"in {timeout:.1f} seconds\n" |
| 47 |
f" before: thread count={orig_count}, dangling={orig_ndangling}\n" |
| 48 |
f" after: thread count={count}, dangling={len(dangling_threads)}") |
| 49 |
for thread in dangling_threads: |
| 50 |
support.print_warning(f"Dangling thread: {thread!r}") |
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
support.gc_collect() |
| 58 |
|
| 59 |
|
| 60 |
def reap_threads(func): |
| 61 |
"""Use this function when threads are being used. This will |
| 62 |
ensure that the threads are cleaned up even when the test fails. |
| 63 |
""" |
| 64 |
@functools.wraps(func) |
| 65 |
def decorator(*args): |
| 66 |
key = threading_setup() |
| 67 |
try: |
| 68 |
return func(*args) |
| 69 |
finally: |
| 70 |
threading_cleanup(*key) |
| 71 |
return decorator |
| 72 |
|
| 73 |
|
| 74 |
@contextlib.contextmanager |
| 75 |
def wait_threads_exit(timeout=None): |
| 76 |
""" |
| 77 |
bpo-31234: Context manager to wait until all threads created in the with |
| 78 |
statement exit. |
| 79 |
|
| 80 |
Use _thread.count() to check if threads exited. Indirectly, wait until |
| 81 |
threads exit the internal t_bootstrap() C function of the _thread module. |
| 82 |
|
| 83 |
threading_setup() and threading_cleanup() are designed to emit a warning |
| 84 |
if a test leaves running threads in the background. This context manager |
| 85 |
is designed to cleanup threads started by the _thread.start_new_thread() |
| 86 |
which doesn't allow to wait for thread exit, whereas thread.Thread has a |
| 87 |
join() method. |
| 88 |
""" |
| 89 |
if timeout is None: |
| 90 |
timeout = support.SHORT_TIMEOUT |
| 91 |
old_count = _thread._count() |
| 92 |
try: |
| 93 |
yield |
| 94 |
finally: |
| 95 |
start_time = time.monotonic() |
| 96 |
for _ in support.sleeping_retry(timeout, error=False): |
| 97 |
support.gc_collect() |
| 98 |
count = _thread._count() |
| 99 |
if count <= old_count: |
| 100 |
break |
| 101 |
else: |
| 102 |
dt = time.monotonic() - start_time |
| 103 |
msg = (f"wait_threads() failed to cleanup {count - old_count} " |
| 104 |
f"threads after {dt:.1f} seconds " |
| 105 |
f"(count: {count}, old count: {old_count})") |
| 106 |
raise AssertionError(msg) |
| 107 |
|
| 108 |
|
| 109 |
def join_thread(thread, timeout=None): |
| 110 |
"""Join a thread. Raise an AssertionError if the thread is still alive |
| 111 |
after timeout seconds. |
| 112 |
""" |
| 113 |
if timeout is None: |
| 114 |
timeout = support.SHORT_TIMEOUT |
| 115 |
thread.join(timeout) |
| 116 |
if thread.is_alive(): |
| 117 |
msg = f"failed to join the thread in {timeout:.1f} seconds" |
| 118 |
raise AssertionError(msg) |
| 119 |
|
| 120 |
|
| 121 |
@contextlib.contextmanager |
| 122 |
def start_threads(threads, unlock=None): |
| 123 |
import faulthandler |
| 124 |
threads = list(threads) |
| 125 |
started = [] |
| 126 |
try: |
| 127 |
try: |
| 128 |
for t in threads: |
| 129 |
t.start() |
| 130 |
started.append(t) |
| 131 |
except: |
| 132 |
if support.verbose: |
| 133 |
print("Can't start %d threads, only %d threads started" % |
| 134 |
(len(threads), len(started))) |
| 135 |
raise |
| 136 |
yield |
| 137 |
finally: |
| 138 |
try: |
| 139 |
if unlock: |
| 140 |
unlock() |
| 141 |
endtime = time.monotonic() |
| 142 |
for timeout in range(1, 16): |
| 143 |
endtime += 60 |
| 144 |
for t in started: |
| 145 |
t.join(max(endtime - time.monotonic(), 0.01)) |
| 146 |
started = [t for t in started if t.is_alive()] |
| 147 |
if not started: |
| 148 |
break |
| 149 |
if support.verbose: |
| 150 |
print('Unable to join %d threads during a period of ' |
| 151 |
'%d minutes' % (len(started), timeout)) |
| 152 |
finally: |
| 153 |
started = [t for t in started if t.is_alive()] |
| 154 |
if started: |
| 155 |
faulthandler.dump_traceback(sys.stdout) |
| 156 |
raise AssertionError('Unable to join %d threads' % len(started)) |
| 157 |
|
| 158 |
|
| 159 |
class catch_threading_exception: |
| 160 |
""" |
| 161 |
Context manager catching threading.Thread exception using |
| 162 |
threading.excepthook. |
| 163 |
|
| 164 |
Attributes set when an exception is caught: |
| 165 |
|
| 166 |
* exc_type |
| 167 |
* exc_value |
| 168 |
* exc_traceback |
| 169 |
* thread |
| 170 |
|
| 171 |
See threading.excepthook() documentation for these attributes. |
| 172 |
|
| 173 |
These attributes are deleted at the context manager exit. |
| 174 |
|
| 175 |
Usage: |
| 176 |
|
| 177 |
with threading_helper.catch_threading_exception() as cm: |
| 178 |
# code spawning a thread which raises an exception |
| 179 |
... |
| 180 |
|
| 181 |
# check the thread exception, use cm attributes: |
| 182 |
# exc_type, exc_value, exc_traceback, thread |
| 183 |
... |
| 184 |
|
| 185 |
# exc_type, exc_value, exc_traceback, thread attributes of cm no longer |
| 186 |
# exists at this point |
| 187 |
# (to avoid reference cycles) |
| 188 |
""" |
| 189 |
|
| 190 |
def __init__(self): |
| 191 |
self.exc_type = None |
| 192 |
self.exc_value = None |
| 193 |
self.exc_traceback = None |
| 194 |
self.thread = None |
| 195 |
self._old_hook = None |
| 196 |
|
| 197 |
def _hook(self, args): |
| 198 |
self.exc_type = args.exc_type |
| 199 |
self.exc_value = args.exc_value |
| 200 |
self.exc_traceback = args.exc_traceback |
| 201 |
self.thread = args.thread |
| 202 |
|
| 203 |
def __enter__(self): |
| 204 |
self._old_hook = threading.excepthook |
| 205 |
threading.excepthook = self._hook |
| 206 |
return self |
| 207 |
|
| 208 |
def __exit__(self, *exc_info): |
| 209 |
threading.excepthook = self._old_hook |
| 210 |
del self.exc_type |
| 211 |
del self.exc_value |
| 212 |
del self.exc_traceback |
| 213 |
del self.thread |
| 214 |
|
| 215 |
|
| 216 |
def _can_start_thread() -> bool: |
| 217 |
"""Detect whether Python can start new threads. |
| 218 |
|
| 219 |
Some WebAssembly platforms do not provide a working pthread |
| 220 |
implementation. Thread support is stubbed and any attempt |
| 221 |
to create a new thread fails. |
| 222 |
|
| 223 |
- wasm32-wasi does not have threading. |
| 224 |
- wasm32-emscripten can be compiled with or without pthread |
| 225 |
support (-s USE_PTHREADS / __EMSCRIPTEN_PTHREADS__). |
| 226 |
""" |
| 227 |
if sys.platform == "emscripten": |
| 228 |
return sys._emscripten_info.pthreads |
| 229 |
elif sys.platform == "wasi": |
| 230 |
return False |
| 231 |
else: |
| 232 |
|
| 233 |
return True |
| 234 |
|
| 235 |
can_start_thread = _can_start_thread() |
| 236 |
|
| 237 |
def requires_working_threading(*, module=False): |
| 238 |
"""Skip tests or modules that require working threading. |
| 239 |
|
| 240 |
Can be used as a function/class decorator or to skip an entire module. |
| 241 |
""" |
| 242 |
msg = "requires threading support" |
| 243 |
if module: |
| 244 |
if not can_start_thread: |
| 245 |
raise unittest.SkipTest(msg) |
| 246 |
else: |
| 247 |
return unittest.skipUnless(can_start_thread, msg) |