| 1 |
import enum |
| 2 |
import errno |
| 3 |
import functools |
| 4 |
import inspect |
| 5 |
import os |
| 6 |
import random |
| 7 |
import signal |
| 8 |
import socket |
| 9 |
import statistics |
| 10 |
import subprocess |
| 11 |
import sys |
| 12 |
import threading |
| 13 |
import time |
| 14 |
import unittest |
| 15 |
from test import support |
| 16 |
from test.support import os_helper, cpython_only |
| 17 |
from test.support.script_helper import assert_python_ok, spawn_python |
| 18 |
from test.support import threading_helper |
| 19 |
try: |
| 20 |
import _testcapi |
| 21 |
except ImportError: |
| 22 |
_testcapi = None |
| 23 |
|
| 24 |
|
| 25 |
class GenericTests(unittest.TestCase): |
| 26 |
|
| 27 |
def test_enums(self): |
| 28 |
for name in dir(signal): |
| 29 |
sig = getattr(signal, name) |
| 30 |
if name in {'SIG_DFL', 'SIG_IGN'}: |
| 31 |
self.assertIsInstance(sig, signal.Handlers) |
| 32 |
elif name in {'SIG_BLOCK', 'SIG_UNBLOCK', 'SIG_SETMASK'}: |
| 33 |
self.assertIsInstance(sig, signal.Sigmasks) |
| 34 |
elif name.startswith('SIG') and not name.startswith('SIG_'): |
| 35 |
self.assertIsInstance(sig, signal.Signals) |
| 36 |
elif name.startswith('CTRL_'): |
| 37 |
self.assertIsInstance(sig, signal.Signals) |
| 38 |
self.assertEqual(sys.platform, "win32") |
| 39 |
|
| 40 |
CheckedSignals = enum._old_convert_( |
| 41 |
enum.IntEnum, 'Signals', 'signal', |
| 42 |
lambda name: |
| 43 |
name.isupper() |
| 44 |
and (name.startswith('SIG') and not name.startswith('SIG_')) |
| 45 |
or name.startswith('CTRL_'), |
| 46 |
source=signal, |
| 47 |
) |
| 48 |
enum._test_simple_enum(CheckedSignals, signal.Signals) |
| 49 |
|
| 50 |
CheckedHandlers = enum._old_convert_( |
| 51 |
enum.IntEnum, 'Handlers', 'signal', |
| 52 |
lambda name: name in ('SIG_DFL', 'SIG_IGN'), |
| 53 |
source=signal, |
| 54 |
) |
| 55 |
enum._test_simple_enum(CheckedHandlers, signal.Handlers) |
| 56 |
|
| 57 |
Sigmasks = getattr(signal, 'Sigmasks', None) |
| 58 |
if Sigmasks is not None: |
| 59 |
CheckedSigmasks = enum._old_convert_( |
| 60 |
enum.IntEnum, 'Sigmasks', 'signal', |
| 61 |
lambda name: name in ('SIG_BLOCK', 'SIG_UNBLOCK', 'SIG_SETMASK'), |
| 62 |
source=signal, |
| 63 |
) |
| 64 |
enum._test_simple_enum(CheckedSigmasks, Sigmasks) |
| 65 |
|
| 66 |
def test_functions_module_attr(self): |
| 67 |
|
| 68 |
|
| 69 |
for name in dir(signal): |
| 70 |
value = getattr(signal, name) |
| 71 |
if inspect.isroutine(value) and not inspect.isbuiltin(value): |
| 72 |
self.assertEqual(value.__module__, 'signal') |
| 73 |
|
| 74 |
|
| 75 |
@unittest.skipIf(sys.platform == "win32", "Not valid on Windows") |
| 76 |
class PosixTests(unittest.TestCase): |
| 77 |
def trivial_signal_handler(self, *args): |
| 78 |
pass |
| 79 |
|
| 80 |
def create_handler_with_partial(self, argument): |
| 81 |
return functools.partial(self.trivial_signal_handler, argument) |
| 82 |
|
| 83 |
def test_out_of_range_signal_number_raises_error(self): |
| 84 |
self.assertRaises(ValueError, signal.getsignal, 4242) |
| 85 |
|
| 86 |
self.assertRaises(ValueError, signal.signal, 4242, |
| 87 |
self.trivial_signal_handler) |
| 88 |
|
| 89 |
self.assertRaises(ValueError, signal.strsignal, 4242) |
| 90 |
|
| 91 |
def test_setting_signal_handler_to_none_raises_error(self): |
| 92 |
self.assertRaises(TypeError, signal.signal, |
| 93 |
signal.SIGUSR1, None) |
| 94 |
|
| 95 |
def test_getsignal(self): |
| 96 |
hup = signal.signal(signal.SIGHUP, self.trivial_signal_handler) |
| 97 |
self.assertIsInstance(hup, signal.Handlers) |
| 98 |
self.assertEqual(signal.getsignal(signal.SIGHUP), |
| 99 |
self.trivial_signal_handler) |
| 100 |
signal.signal(signal.SIGHUP, hup) |
| 101 |
self.assertEqual(signal.getsignal(signal.SIGHUP), hup) |
| 102 |
|
| 103 |
def test_no_repr_is_called_on_signal_handler(self): |
| 104 |
|
| 105 |
|
| 106 |
class MyArgument: |
| 107 |
def __init__(self): |
| 108 |
self.repr_count = 0 |
| 109 |
|
| 110 |
def __repr__(self): |
| 111 |
self.repr_count += 1 |
| 112 |
return super().__repr__() |
| 113 |
|
| 114 |
argument = MyArgument() |
| 115 |
self.assertEqual(0, argument.repr_count) |
| 116 |
|
| 117 |
handler = self.create_handler_with_partial(argument) |
| 118 |
hup = signal.signal(signal.SIGHUP, handler) |
| 119 |
self.assertIsInstance(hup, signal.Handlers) |
| 120 |
self.assertEqual(signal.getsignal(signal.SIGHUP), handler) |
| 121 |
signal.signal(signal.SIGHUP, hup) |
| 122 |
self.assertEqual(signal.getsignal(signal.SIGHUP), hup) |
| 123 |
self.assertEqual(0, argument.repr_count) |
| 124 |
|
| 125 |
def test_strsignal(self): |
| 126 |
self.assertIn("Interrupt", signal.strsignal(signal.SIGINT)) |
| 127 |
self.assertIn("Terminated", signal.strsignal(signal.SIGTERM)) |
| 128 |
self.assertIn("Hangup", signal.strsignal(signal.SIGHUP)) |
| 129 |
|
| 130 |
|
| 131 |
def test_interprocess_signal(self): |
| 132 |
dirname = os.path.dirname(__file__) |
| 133 |
script = os.path.join(dirname, 'signalinterproctester.py') |
| 134 |
assert_python_ok(script) |
| 135 |
|
| 136 |
@unittest.skipUnless( |
| 137 |
hasattr(signal, "valid_signals"), |
| 138 |
"requires signal.valid_signals" |
| 139 |
) |
| 140 |
def test_valid_signals(self): |
| 141 |
s = signal.valid_signals() |
| 142 |
self.assertIsInstance(s, set) |
| 143 |
self.assertIn(signal.Signals.SIGINT, s) |
| 144 |
self.assertIn(signal.Signals.SIGALRM, s) |
| 145 |
self.assertNotIn(0, s) |
| 146 |
self.assertNotIn(signal.NSIG, s) |
| 147 |
self.assertLess(len(s), signal.NSIG) |
| 148 |
|
| 149 |
|
| 150 |
|
| 151 |
for name in dir(signal): |
| 152 |
if not name.startswith("SIG"): |
| 153 |
continue |
| 154 |
if name in {"SIG_IGN", "SIG_DFL"}: |
| 155 |
|
| 156 |
continue |
| 157 |
with self.subTest(name=name): |
| 158 |
signum = getattr(signal, name) |
| 159 |
self.assertGreaterEqual(signum, 0) |
| 160 |
self.assertLess(signum, signal.NSIG) |
| 161 |
|
| 162 |
@unittest.skipUnless(sys.executable, "sys.executable required.") |
| 163 |
@support.requires_subprocess() |
| 164 |
def test_keyboard_interrupt_exit_code(self): |
| 165 |
"""KeyboardInterrupt triggers exit via SIGINT.""" |
| 166 |
process = subprocess.run( |
| 167 |
[sys.executable, "-c", |
| 168 |
"import os, signal, time\n" |
| 169 |
"os.kill(os.getpid(), signal.SIGINT)\n" |
| 170 |
"for _ in range(999): time.sleep(0.01)"], |
| 171 |
stderr=subprocess.PIPE) |
| 172 |
self.assertIn(b"KeyboardInterrupt", process.stderr) |
| 173 |
self.assertEqual(process.returncode, -signal.SIGINT) |
| 174 |
|
| 175 |
|
| 176 |
|
| 177 |
|
| 178 |
|
| 179 |
|
| 180 |
@unittest.skipUnless(sys.platform == "win32", "Windows specific") |
| 181 |
class WindowsSignalTests(unittest.TestCase): |
| 182 |
|
| 183 |
def test_valid_signals(self): |
| 184 |
s = signal.valid_signals() |
| 185 |
self.assertIsInstance(s, set) |
| 186 |
self.assertGreaterEqual(len(s), 6) |
| 187 |
self.assertIn(signal.Signals.SIGINT, s) |
| 188 |
self.assertNotIn(0, s) |
| 189 |
self.assertNotIn(signal.NSIG, s) |
| 190 |
self.assertLess(len(s), signal.NSIG) |
| 191 |
|
| 192 |
def test_issue9324(self): |
| 193 |
|
| 194 |
handler = lambda x, y: None |
| 195 |
checked = set() |
| 196 |
for sig in (signal.SIGABRT, signal.SIGBREAK, signal.SIGFPE, |
| 197 |
signal.SIGILL, signal.SIGINT, signal.SIGSEGV, |
| 198 |
signal.SIGTERM): |
| 199 |
|
| 200 |
|
| 201 |
if signal.getsignal(sig) is not None: |
| 202 |
signal.signal(sig, signal.signal(sig, handler)) |
| 203 |
checked.add(sig) |
| 204 |
|
| 205 |
self.assertTrue(checked) |
| 206 |
|
| 207 |
with self.assertRaises(ValueError): |
| 208 |
signal.signal(-1, handler) |
| 209 |
|
| 210 |
with self.assertRaises(ValueError): |
| 211 |
signal.signal(7, handler) |
| 212 |
|
| 213 |
@unittest.skipUnless(sys.executable, "sys.executable required.") |
| 214 |
@support.requires_subprocess() |
| 215 |
def test_keyboard_interrupt_exit_code(self): |
| 216 |
"""KeyboardInterrupt triggers an exit using STATUS_CONTROL_C_EXIT.""" |
| 217 |
|
| 218 |
|
| 219 |
|
| 220 |
|
| 221 |
process = subprocess.run( |
| 222 |
[sys.executable, "-c", "raise KeyboardInterrupt"], |
| 223 |
stderr=subprocess.PIPE) |
| 224 |
self.assertIn(b"KeyboardInterrupt", process.stderr) |
| 225 |
STATUS_CONTROL_C_EXIT = 0xC000013A |
| 226 |
self.assertEqual(process.returncode, STATUS_CONTROL_C_EXIT) |
| 227 |
|
| 228 |
|
| 229 |
class WakeupFDTests(unittest.TestCase): |
| 230 |
|
| 231 |
def test_invalid_call(self): |
| 232 |
|
| 233 |
with self.assertRaises(TypeError): |
| 234 |
signal.set_wakeup_fd(signum=signal.SIGINT) |
| 235 |
|
| 236 |
|
| 237 |
with self.assertRaises(TypeError): |
| 238 |
signal.set_wakeup_fd(signal.SIGINT, False) |
| 239 |
|
| 240 |
def test_invalid_fd(self): |
| 241 |
fd = os_helper.make_bad_fd() |
| 242 |
self.assertRaises((ValueError, OSError), |
| 243 |
signal.set_wakeup_fd, fd) |
| 244 |
|
| 245 |
@unittest.skipUnless(support.has_socket_support, "needs working sockets.") |
| 246 |
def test_invalid_socket(self): |
| 247 |
sock = socket.socket() |
| 248 |
fd = sock.fileno() |
| 249 |
sock.close() |
| 250 |
self.assertRaises((ValueError, OSError), |
| 251 |
signal.set_wakeup_fd, fd) |
| 252 |
|
| 253 |
|
| 254 |
|
| 255 |
@unittest.skipIf(support.is_emscripten, "Emscripten cannot fstat pipes.") |
| 256 |
@unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()") |
| 257 |
def test_set_wakeup_fd_result(self): |
| 258 |
r1, w1 = os.pipe() |
| 259 |
self.addCleanup(os.close, r1) |
| 260 |
self.addCleanup(os.close, w1) |
| 261 |
r2, w2 = os.pipe() |
| 262 |
self.addCleanup(os.close, r2) |
| 263 |
self.addCleanup(os.close, w2) |
| 264 |
|
| 265 |
if hasattr(os, 'set_blocking'): |
| 266 |
os.set_blocking(w1, False) |
| 267 |
os.set_blocking(w2, False) |
| 268 |
|
| 269 |
signal.set_wakeup_fd(w1) |
| 270 |
self.assertEqual(signal.set_wakeup_fd(w2), w1) |
| 271 |
self.assertEqual(signal.set_wakeup_fd(-1), w2) |
| 272 |
self.assertEqual(signal.set_wakeup_fd(-1), -1) |
| 273 |
|
| 274 |
@unittest.skipIf(support.is_emscripten, "Emscripten cannot fstat pipes.") |
| 275 |
@unittest.skipUnless(support.has_socket_support, "needs working sockets.") |
| 276 |
def test_set_wakeup_fd_socket_result(self): |
| 277 |
sock1 = socket.socket() |
| 278 |
self.addCleanup(sock1.close) |
| 279 |
sock1.setblocking(False) |
| 280 |
fd1 = sock1.fileno() |
| 281 |
|
| 282 |
sock2 = socket.socket() |
| 283 |
self.addCleanup(sock2.close) |
| 284 |
sock2.setblocking(False) |
| 285 |
fd2 = sock2.fileno() |
| 286 |
|
| 287 |
signal.set_wakeup_fd(fd1) |
| 288 |
self.assertEqual(signal.set_wakeup_fd(fd2), fd1) |
| 289 |
self.assertEqual(signal.set_wakeup_fd(-1), fd2) |
| 290 |
self.assertEqual(signal.set_wakeup_fd(-1), -1) |
| 291 |
|
| 292 |
|
| 293 |
|
| 294 |
@unittest.skipIf(sys.platform == "win32", "tests specific to POSIX") |
| 295 |
@unittest.skipIf(support.is_emscripten, "Emscripten cannot fstat pipes.") |
| 296 |
@unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()") |
| 297 |
def test_set_wakeup_fd_blocking(self): |
| 298 |
rfd, wfd = os.pipe() |
| 299 |
self.addCleanup(os.close, rfd) |
| 300 |
self.addCleanup(os.close, wfd) |
| 301 |
|
| 302 |
|
| 303 |
os.set_blocking(wfd, True) |
| 304 |
with self.assertRaises(ValueError) as cm: |
| 305 |
signal.set_wakeup_fd(wfd) |
| 306 |
self.assertEqual(str(cm.exception), |
| 307 |
"the fd %s must be in non-blocking mode" % wfd) |
| 308 |
|
| 309 |
|
| 310 |
os.set_blocking(wfd, False) |
| 311 |
signal.set_wakeup_fd(wfd) |
| 312 |
signal.set_wakeup_fd(-1) |
| 313 |
|
| 314 |
|
| 315 |
@unittest.skipIf(sys.platform == "win32", "Not valid on Windows") |
| 316 |
class WakeupSignalTests(unittest.TestCase): |
| 317 |
@unittest.skipIf(_testcapi is None, 'need _testcapi') |
| 318 |
def check_wakeup(self, test_body, *signals, ordered=True): |
| 319 |
|
| 320 |
code = """if 1: |
| 321 |
import _testcapi |
| 322 |
import os |
| 323 |
import signal |
| 324 |
import struct |
| 325 |
|
| 326 |
signals = {!r} |
| 327 |
|
| 328 |
def handler(signum, frame): |
| 329 |
pass |
| 330 |
|
| 331 |
def check_signum(signals): |
| 332 |
data = os.read(read, len(signals)+1) |
| 333 |
raised = struct.unpack('%uB' % len(data), data) |
| 334 |
if not {!r}: |
| 335 |
raised = set(raised) |
| 336 |
signals = set(signals) |
| 337 |
if raised != signals: |
| 338 |
raise Exception("%r != %r" % (raised, signals)) |
| 339 |
|
| 340 |
{} |
| 341 |
|
| 342 |
signal.signal(signal.SIGALRM, handler) |
| 343 |
read, write = os.pipe() |
| 344 |
os.set_blocking(write, False) |
| 345 |
signal.set_wakeup_fd(write) |
| 346 |
|
| 347 |
test() |
| 348 |
check_signum(signals) |
| 349 |
|
| 350 |
os.close(read) |
| 351 |
os.close(write) |
| 352 |
""".format(tuple(map(int, signals)), ordered, test_body) |
| 353 |
|
| 354 |
assert_python_ok('-c', code) |
| 355 |
|
| 356 |
@unittest.skipIf(_testcapi is None, 'need _testcapi') |
| 357 |
@unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()") |
| 358 |
def test_wakeup_write_error(self): |
| 359 |
|
| 360 |
|
| 361 |
|
| 362 |
code = """if 1: |
| 363 |
import _testcapi |
| 364 |
import errno |
| 365 |
import os |
| 366 |
import signal |
| 367 |
import sys |
| 368 |
from test.support import captured_stderr |
| 369 |
|
| 370 |
def handler(signum, frame): |
| 371 |
1/0 |
| 372 |
|
| 373 |
signal.signal(signal.SIGALRM, handler) |
| 374 |
r, w = os.pipe() |
| 375 |
os.set_blocking(r, False) |
| 376 |
|
| 377 |
# Set wakeup_fd a read-only file descriptor to trigger the error |
| 378 |
signal.set_wakeup_fd(r) |
| 379 |
try: |
| 380 |
with captured_stderr() as err: |
| 381 |
signal.raise_signal(signal.SIGALRM) |
| 382 |
except ZeroDivisionError: |
| 383 |
# An ignored exception should have been printed out on stderr |
| 384 |
err = err.getvalue() |
| 385 |
if ('Exception ignored when trying to write to the signal wakeup fd' |
| 386 |
not in err): |
| 387 |
raise AssertionError(err) |
| 388 |
if ('OSError: [Errno %d]' % errno.EBADF) not in err: |
| 389 |
raise AssertionError(err) |
| 390 |
else: |
| 391 |
raise AssertionError("ZeroDivisionError not raised") |
| 392 |
|
| 393 |
os.close(r) |
| 394 |
os.close(w) |
| 395 |
""" |
| 396 |
r, w = os.pipe() |
| 397 |
try: |
| 398 |
os.write(r, b'x') |
| 399 |
except OSError: |
| 400 |
pass |
| 401 |
else: |
| 402 |
self.skipTest("OS doesn't report write() error on the read end of a pipe") |
| 403 |
finally: |
| 404 |
os.close(r) |
| 405 |
os.close(w) |
| 406 |
|
| 407 |
assert_python_ok('-c', code) |
| 408 |
|
| 409 |
def test_wakeup_fd_early(self): |
| 410 |
self.check_wakeup("""def test(): |
| 411 |
import select |
| 412 |
import time |
| 413 |
|
| 414 |
TIMEOUT_FULL = 10 |
| 415 |
TIMEOUT_HALF = 5 |
| 416 |
|
| 417 |
class InterruptSelect(Exception): |
| 418 |
pass |
| 419 |
|
| 420 |
def handler(signum, frame): |
| 421 |
raise InterruptSelect |
| 422 |
signal.signal(signal.SIGALRM, handler) |
| 423 |
|
| 424 |
signal.alarm(1) |
| 425 |
|
| 426 |
# We attempt to get a signal during the sleep, |
| 427 |
# before select is called |
| 428 |
try: |
| 429 |
select.select([], [], [], TIMEOUT_FULL) |
| 430 |
except InterruptSelect: |
| 431 |
pass |
| 432 |
else: |
| 433 |
raise Exception("select() was not interrupted") |
| 434 |
|
| 435 |
before_time = time.monotonic() |
| 436 |
select.select([read], [], [], TIMEOUT_FULL) |
| 437 |
after_time = time.monotonic() |
| 438 |
dt = after_time - before_time |
| 439 |
if dt >= TIMEOUT_HALF: |
| 440 |
raise Exception("%s >= %s" % (dt, TIMEOUT_HALF)) |
| 441 |
""", signal.SIGALRM) |
| 442 |
|
| 443 |
def test_wakeup_fd_during(self): |
| 444 |
self.check_wakeup("""def test(): |
| 445 |
import select |
| 446 |
import time |
| 447 |
|
| 448 |
TIMEOUT_FULL = 10 |
| 449 |
TIMEOUT_HALF = 5 |
| 450 |
|
| 451 |
class InterruptSelect(Exception): |
| 452 |
pass |
| 453 |
|
| 454 |
def handler(signum, frame): |
| 455 |
raise InterruptSelect |
| 456 |
signal.signal(signal.SIGALRM, handler) |
| 457 |
|
| 458 |
signal.alarm(1) |
| 459 |
before_time = time.monotonic() |
| 460 |
# We attempt to get a signal during the select call |
| 461 |
try: |
| 462 |
select.select([read], [], [], TIMEOUT_FULL) |
| 463 |
except InterruptSelect: |
| 464 |
pass |
| 465 |
else: |
| 466 |
raise Exception("select() was not interrupted") |
| 467 |
after_time = time.monotonic() |
| 468 |
dt = after_time - before_time |
| 469 |
if dt >= TIMEOUT_HALF: |
| 470 |
raise Exception("%s >= %s" % (dt, TIMEOUT_HALF)) |
| 471 |
""", signal.SIGALRM) |
| 472 |
|
| 473 |
def test_signum(self): |
| 474 |
self.check_wakeup("""def test(): |
| 475 |
signal.signal(signal.SIGUSR1, handler) |
| 476 |
signal.raise_signal(signal.SIGUSR1) |
| 477 |
signal.raise_signal(signal.SIGALRM) |
| 478 |
""", signal.SIGUSR1, signal.SIGALRM) |
| 479 |
|
| 480 |
@unittest.skipUnless(hasattr(signal, 'pthread_sigmask'), |
| 481 |
'need signal.pthread_sigmask()') |
| 482 |
def test_pending(self): |
| 483 |
self.check_wakeup("""def test(): |
| 484 |
signum1 = signal.SIGUSR1 |
| 485 |
signum2 = signal.SIGUSR2 |
| 486 |
|
| 487 |
signal.signal(signum1, handler) |
| 488 |
signal.signal(signum2, handler) |
| 489 |
|
| 490 |
signal.pthread_sigmask(signal.SIG_BLOCK, (signum1, signum2)) |
| 491 |
signal.raise_signal(signum1) |
| 492 |
signal.raise_signal(signum2) |
| 493 |
# Unblocking the 2 signals calls the C signal handler twice |
| 494 |
signal.pthread_sigmask(signal.SIG_UNBLOCK, (signum1, signum2)) |
| 495 |
""", signal.SIGUSR1, signal.SIGUSR2, ordered=False) |
| 496 |
|
| 497 |
|
| 498 |
@unittest.skipUnless(hasattr(socket, 'socketpair'), 'need socket.socketpair') |
| 499 |
class WakeupSocketSignalTests(unittest.TestCase): |
| 500 |
|
| 501 |
@unittest.skipIf(_testcapi is None, 'need _testcapi') |
| 502 |
def test_socket(self): |
| 503 |
|
| 504 |
code = """if 1: |
| 505 |
import signal |
| 506 |
import socket |
| 507 |
import struct |
| 508 |
import _testcapi |
| 509 |
|
| 510 |
signum = signal.SIGINT |
| 511 |
signals = (signum,) |
| 512 |
|
| 513 |
def handler(signum, frame): |
| 514 |
pass |
| 515 |
|
| 516 |
signal.signal(signum, handler) |
| 517 |
|
| 518 |
read, write = socket.socketpair() |
| 519 |
write.setblocking(False) |
| 520 |
signal.set_wakeup_fd(write.fileno()) |
| 521 |
|
| 522 |
signal.raise_signal(signum) |
| 523 |
|
| 524 |
data = read.recv(1) |
| 525 |
if not data: |
| 526 |
raise Exception("no signum written") |
| 527 |
raised = struct.unpack('B', data) |
| 528 |
if raised != signals: |
| 529 |
raise Exception("%r != %r" % (raised, signals)) |
| 530 |
|
| 531 |
read.close() |
| 532 |
write.close() |
| 533 |
""" |
| 534 |
|
| 535 |
assert_python_ok('-c', code) |
| 536 |
|
| 537 |
@unittest.skipIf(_testcapi is None, 'need _testcapi') |
| 538 |
def test_send_error(self): |
| 539 |
|
| 540 |
if os.name == 'nt': |
| 541 |
action = 'send' |
| 542 |
else: |
| 543 |
action = 'write' |
| 544 |
code = """if 1: |
| 545 |
import errno |
| 546 |
import signal |
| 547 |
import socket |
| 548 |
import sys |
| 549 |
import time |
| 550 |
import _testcapi |
| 551 |
from test.support import captured_stderr |
| 552 |
|
| 553 |
signum = signal.SIGINT |
| 554 |
|
| 555 |
def handler(signum, frame): |
| 556 |
pass |
| 557 |
|
| 558 |
signal.signal(signum, handler) |
| 559 |
|
| 560 |
read, write = socket.socketpair() |
| 561 |
read.setblocking(False) |
| 562 |
write.setblocking(False) |
| 563 |
|
| 564 |
signal.set_wakeup_fd(write.fileno()) |
| 565 |
|
| 566 |
# Close sockets: send() will fail |
| 567 |
read.close() |
| 568 |
write.close() |
| 569 |
|
| 570 |
with captured_stderr() as err: |
| 571 |
signal.raise_signal(signum) |
| 572 |
|
| 573 |
err = err.getvalue() |
| 574 |
if ('Exception ignored when trying to {action} to the signal wakeup fd' |
| 575 |
not in err): |
| 576 |
raise AssertionError(err) |
| 577 |
""".format(action=action) |
| 578 |
assert_python_ok('-c', code) |
| 579 |
|
| 580 |
@unittest.skipIf(_testcapi is None, 'need _testcapi') |
| 581 |
def test_warn_on_full_buffer(self): |
| 582 |
|
| 583 |
if os.name == 'nt': |
| 584 |
action = 'send' |
| 585 |
else: |
| 586 |
action = 'write' |
| 587 |
code = """if 1: |
| 588 |
import errno |
| 589 |
import signal |
| 590 |
import socket |
| 591 |
import sys |
| 592 |
import time |
| 593 |
import _testcapi |
| 594 |
from test.support import captured_stderr |
| 595 |
|
| 596 |
signum = signal.SIGINT |
| 597 |
|
| 598 |
# This handler will be called, but we intentionally won't read from |
| 599 |
# the wakeup fd. |
| 600 |
def handler(signum, frame): |
| 601 |
pass |
| 602 |
|
| 603 |
signal.signal(signum, handler) |
| 604 |
|
| 605 |
read, write = socket.socketpair() |
| 606 |
|
| 607 |
# Fill the socketpair buffer |
| 608 |
if sys.platform == 'win32': |
| 609 |
# bpo-34130: On Windows, sometimes non-blocking send fails to fill |
| 610 |
# the full socketpair buffer, so use a timeout of 50 ms instead. |
| 611 |
write.settimeout(0.050) |
| 612 |
else: |
| 613 |
write.setblocking(False) |
| 614 |
|
| 615 |
written = 0 |
| 616 |
if sys.platform == "vxworks": |
| 617 |
CHUNK_SIZES = (1,) |
| 618 |
else: |
| 619 |
# Start with large chunk size to reduce the |
| 620 |
# number of send needed to fill the buffer. |
| 621 |
CHUNK_SIZES = (2 ** 16, 2 ** 8, 1) |
| 622 |
for chunk_size in CHUNK_SIZES: |
| 623 |
chunk = b"x" * chunk_size |
| 624 |
try: |
| 625 |
while True: |
| 626 |
write.send(chunk) |
| 627 |
written += chunk_size |
| 628 |
except (BlockingIOError, TimeoutError): |
| 629 |
pass |
| 630 |
|
| 631 |
print(f"%s bytes written into the socketpair" % written, flush=True) |
| 632 |
|
| 633 |
write.setblocking(False) |
| 634 |
try: |
| 635 |
write.send(b"x") |
| 636 |
except BlockingIOError: |
| 637 |
# The socketpair buffer seems full |
| 638 |
pass |
| 639 |
else: |
| 640 |
raise AssertionError("%s bytes failed to fill the socketpair " |
| 641 |
"buffer" % written) |
| 642 |
|
| 643 |
# By default, we get a warning when a signal arrives |
| 644 |
msg = ('Exception ignored when trying to {action} ' |
| 645 |
'to the signal wakeup fd') |
| 646 |
signal.set_wakeup_fd(write.fileno()) |
| 647 |
|
| 648 |
with captured_stderr() as err: |
| 649 |
signal.raise_signal(signum) |
| 650 |
|
| 651 |
err = err.getvalue() |
| 652 |
if msg not in err: |
| 653 |
raise AssertionError("first set_wakeup_fd() test failed, " |
| 654 |
"stderr: %r" % err) |
| 655 |
|
| 656 |
# And also if warn_on_full_buffer=True |
| 657 |
signal.set_wakeup_fd(write.fileno(), warn_on_full_buffer=True) |
| 658 |
|
| 659 |
with captured_stderr() as err: |
| 660 |
signal.raise_signal(signum) |
| 661 |
|
| 662 |
err = err.getvalue() |
| 663 |
if msg not in err: |
| 664 |
raise AssertionError("set_wakeup_fd(warn_on_full_buffer=True) " |
| 665 |
"test failed, stderr: %r" % err) |
| 666 |
|
| 667 |
# But not if warn_on_full_buffer=False |
| 668 |
signal.set_wakeup_fd(write.fileno(), warn_on_full_buffer=False) |
| 669 |
|
| 670 |
with captured_stderr() as err: |
| 671 |
signal.raise_signal(signum) |
| 672 |
|
| 673 |
err = err.getvalue() |
| 674 |
if err != "": |
| 675 |
raise AssertionError("set_wakeup_fd(warn_on_full_buffer=False) " |
| 676 |
"test failed, stderr: %r" % err) |
| 677 |
|
| 678 |
# And then check the default again, to make sure warn_on_full_buffer |
| 679 |
# settings don't leak across calls. |
| 680 |
signal.set_wakeup_fd(write.fileno()) |
| 681 |
|
| 682 |
with captured_stderr() as err: |
| 683 |
signal.raise_signal(signum) |
| 684 |
|
| 685 |
err = err.getvalue() |
| 686 |
if msg not in err: |
| 687 |
raise AssertionError("second set_wakeup_fd() test failed, " |
| 688 |
"stderr: %r" % err) |
| 689 |
|
| 690 |
""".format(action=action) |
| 691 |
assert_python_ok('-c', code) |
| 692 |
|
| 693 |
|
| 694 |
@unittest.skipIf(sys.platform == "win32", "Not valid on Windows") |
| 695 |
@unittest.skipUnless(hasattr(signal, 'siginterrupt'), "needs signal.siginterrupt()") |
| 696 |
@support.requires_subprocess() |
| 697 |
@unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()") |
| 698 |
class SiginterruptTest(unittest.TestCase): |
| 699 |
|
| 700 |
def readpipe_interrupted(self, interrupt): |
| 701 |
"""Perform a read during which a signal will arrive. Return True if the |
| 702 |
read is interrupted by the signal and raises an exception. Return False |
| 703 |
if it returns normally. |
| 704 |
""" |
| 705 |
|
| 706 |
|
| 707 |
code = """if 1: |
| 708 |
import errno |
| 709 |
import os |
| 710 |
import signal |
| 711 |
import sys |
| 712 |
|
| 713 |
interrupt = %r |
| 714 |
r, w = os.pipe() |
| 715 |
|
| 716 |
def handler(signum, frame): |
| 717 |
1 / 0 |
| 718 |
|
| 719 |
signal.signal(signal.SIGALRM, handler) |
| 720 |
if interrupt is not None: |
| 721 |
signal.siginterrupt(signal.SIGALRM, interrupt) |
| 722 |
|
| 723 |
print("ready") |
| 724 |
sys.stdout.flush() |
| 725 |
|
| 726 |
# run the test twice |
| 727 |
try: |
| 728 |
for loop in range(2): |
| 729 |
# send a SIGALRM in a second (during the read) |
| 730 |
signal.alarm(1) |
| 731 |
try: |
| 732 |
# blocking call: read from a pipe without data |
| 733 |
os.read(r, 1) |
| 734 |
except ZeroDivisionError: |
| 735 |
pass |
| 736 |
else: |
| 737 |
sys.exit(2) |
| 738 |
sys.exit(3) |
| 739 |
finally: |
| 740 |
os.close(r) |
| 741 |
os.close(w) |
| 742 |
""" % (interrupt,) |
| 743 |
with spawn_python('-c', code) as process: |
| 744 |
try: |
| 745 |
|
| 746 |
first_line = process.stdout.readline() |
| 747 |
|
| 748 |
stdout, stderr = process.communicate(timeout=support.SHORT_TIMEOUT) |
| 749 |
except subprocess.TimeoutExpired: |
| 750 |
process.kill() |
| 751 |
return False |
| 752 |
else: |
| 753 |
stdout = first_line + stdout |
| 754 |
exitcode = process.wait() |
| 755 |
if exitcode not in (2, 3): |
| 756 |
raise Exception("Child error (exit code %s): %r" |
| 757 |
% (exitcode, stdout)) |
| 758 |
return (exitcode == 3) |
| 759 |
|
| 760 |
def test_without_siginterrupt(self): |
| 761 |
|
| 762 |
|
| 763 |
|
| 764 |
interrupted = self.readpipe_interrupted(None) |
| 765 |
self.assertTrue(interrupted) |
| 766 |
|
| 767 |
def test_siginterrupt_on(self): |
| 768 |
|
| 769 |
|
| 770 |
|
| 771 |
interrupted = self.readpipe_interrupted(True) |
| 772 |
self.assertTrue(interrupted) |
| 773 |
|
| 774 |
@support.requires_resource('walltime') |
| 775 |
def test_siginterrupt_off(self): |
| 776 |
|
| 777 |
|
| 778 |
|
| 779 |
interrupted = self.readpipe_interrupted(False) |
| 780 |
self.assertFalse(interrupted) |
| 781 |
|
| 782 |
|
| 783 |
@unittest.skipIf(sys.platform == "win32", "Not valid on Windows") |
| 784 |
@unittest.skipUnless(hasattr(signal, 'getitimer') and hasattr(signal, 'setitimer'), |
| 785 |
"needs signal.getitimer() and signal.setitimer()") |
| 786 |
class ItimerTest(unittest.TestCase): |
| 787 |
def setUp(self): |
| 788 |
self.hndl_called = False |
| 789 |
self.hndl_count = 0 |
| 790 |
self.itimer = None |
| 791 |
self.old_alarm = signal.signal(signal.SIGALRM, self.sig_alrm) |
| 792 |
|
| 793 |
def tearDown(self): |
| 794 |
signal.signal(signal.SIGALRM, self.old_alarm) |
| 795 |
if self.itimer is not None: |
| 796 |
|
| 797 |
signal.setitimer(self.itimer, 0) |
| 798 |
|
| 799 |
def sig_alrm(self, *args): |
| 800 |
self.hndl_called = True |
| 801 |
|
| 802 |
def sig_vtalrm(self, *args): |
| 803 |
self.hndl_called = True |
| 804 |
|
| 805 |
if self.hndl_count > 3: |
| 806 |
|
| 807 |
raise signal.ItimerError("setitimer didn't disable ITIMER_VIRTUAL " |
| 808 |
"timer.") |
| 809 |
elif self.hndl_count == 3: |
| 810 |
|
| 811 |
signal.setitimer(signal.ITIMER_VIRTUAL, 0) |
| 812 |
|
| 813 |
self.hndl_count += 1 |
| 814 |
|
| 815 |
def sig_prof(self, *args): |
| 816 |
self.hndl_called = True |
| 817 |
signal.setitimer(signal.ITIMER_PROF, 0) |
| 818 |
|
| 819 |
def test_itimer_exc(self): |
| 820 |
|
| 821 |
|
| 822 |
self.assertRaises(signal.ItimerError, signal.setitimer, -1, 0) |
| 823 |
|
| 824 |
if 0: |
| 825 |
self.assertRaises(signal.ItimerError, |
| 826 |
signal.setitimer, signal.ITIMER_REAL, -1) |
| 827 |
|
| 828 |
def test_itimer_real(self): |
| 829 |
self.itimer = signal.ITIMER_REAL |
| 830 |
signal.setitimer(self.itimer, 1.0) |
| 831 |
signal.pause() |
| 832 |
self.assertEqual(self.hndl_called, True) |
| 833 |
|
| 834 |
|
| 835 |
@unittest.skipIf(sys.platform in ('netbsd5',), |
| 836 |
'itimer not reliable (does not mix well with threading) on some BSDs.') |
| 837 |
def test_itimer_virtual(self): |
| 838 |
self.itimer = signal.ITIMER_VIRTUAL |
| 839 |
signal.signal(signal.SIGVTALRM, self.sig_vtalrm) |
| 840 |
signal.setitimer(self.itimer, 0.3, 0.2) |
| 841 |
|
| 842 |
for _ in support.busy_retry(60.0, error=False): |
| 843 |
|
| 844 |
_ = pow(12345, 67890, 10000019) |
| 845 |
if signal.getitimer(self.itimer) == (0.0, 0.0): |
| 846 |
|
| 847 |
break |
| 848 |
else: |
| 849 |
|
| 850 |
self.skipTest("timeout: likely cause: machine too slow or load too " |
| 851 |
"high") |
| 852 |
|
| 853 |
|
| 854 |
self.assertEqual(signal.getitimer(self.itimer), (0.0, 0.0)) |
| 855 |
|
| 856 |
self.assertEqual(self.hndl_called, True) |
| 857 |
|
| 858 |
def test_itimer_prof(self): |
| 859 |
self.itimer = signal.ITIMER_PROF |
| 860 |
signal.signal(signal.SIGPROF, self.sig_prof) |
| 861 |
signal.setitimer(self.itimer, 0.2, 0.2) |
| 862 |
|
| 863 |
for _ in support.busy_retry(60.0, error=False): |
| 864 |
|
| 865 |
_ = pow(12345, 67890, 10000019) |
| 866 |
if signal.getitimer(self.itimer) == (0.0, 0.0): |
| 867 |
|
| 868 |
break |
| 869 |
else: |
| 870 |
|
| 871 |
self.skipTest("timeout: likely cause: machine too slow or load too " |
| 872 |
"high") |
| 873 |
|
| 874 |
|
| 875 |
self.assertEqual(signal.getitimer(self.itimer), (0.0, 0.0)) |
| 876 |
|
| 877 |
self.assertEqual(self.hndl_called, True) |
| 878 |
|
| 879 |
def test_setitimer_tiny(self): |
| 880 |
|
| 881 |
|
| 882 |
|
| 883 |
self.itimer = signal.ITIMER_REAL |
| 884 |
signal.setitimer(self.itimer, 1e-6) |
| 885 |
time.sleep(1) |
| 886 |
self.assertEqual(self.hndl_called, True) |
| 887 |
|
| 888 |
|
| 889 |
class PendingSignalsTests(unittest.TestCase): |
| 890 |
""" |
| 891 |
Test pthread_sigmask(), pthread_kill(), sigpending() and sigwait() |
| 892 |
functions. |
| 893 |
""" |
| 894 |
@unittest.skipUnless(hasattr(signal, 'sigpending'), |
| 895 |
'need signal.sigpending()') |
| 896 |
def test_sigpending_empty(self): |
| 897 |
self.assertEqual(signal.sigpending(), set()) |
| 898 |
|
| 899 |
@unittest.skipUnless(hasattr(signal, 'pthread_sigmask'), |
| 900 |
'need signal.pthread_sigmask()') |
| 901 |
@unittest.skipUnless(hasattr(signal, 'sigpending'), |
| 902 |
'need signal.sigpending()') |
| 903 |
def test_sigpending(self): |
| 904 |
code = """if 1: |
| 905 |
import os |
| 906 |
import signal |
| 907 |
|
| 908 |
def handler(signum, frame): |
| 909 |
1/0 |
| 910 |
|
| 911 |
signum = signal.SIGUSR1 |
| 912 |
signal.signal(signum, handler) |
| 913 |
|
| 914 |
signal.pthread_sigmask(signal.SIG_BLOCK, [signum]) |
| 915 |
os.kill(os.getpid(), signum) |
| 916 |
pending = signal.sigpending() |
| 917 |
for sig in pending: |
| 918 |
assert isinstance(sig, signal.Signals), repr(pending) |
| 919 |
if pending != {signum}: |
| 920 |
raise Exception('%s != {%s}' % (pending, signum)) |
| 921 |
try: |
| 922 |
signal.pthread_sigmask(signal.SIG_UNBLOCK, [signum]) |
| 923 |
except ZeroDivisionError: |
| 924 |
pass |
| 925 |
else: |
| 926 |
raise Exception("ZeroDivisionError not raised") |
| 927 |
""" |
| 928 |
assert_python_ok('-c', code) |
| 929 |
|
| 930 |
@unittest.skipUnless(hasattr(signal, 'pthread_kill'), |
| 931 |
'need signal.pthread_kill()') |
| 932 |
@threading_helper.requires_working_threading() |
| 933 |
def test_pthread_kill(self): |
| 934 |
code = """if 1: |
| 935 |
import signal |
| 936 |
import threading |
| 937 |
import sys |
| 938 |
|
| 939 |
signum = signal.SIGUSR1 |
| 940 |
|
| 941 |
def handler(signum, frame): |
| 942 |
1/0 |
| 943 |
|
| 944 |
signal.signal(signum, handler) |
| 945 |
|
| 946 |
tid = threading.get_ident() |
| 947 |
try: |
| 948 |
signal.pthread_kill(tid, signum) |
| 949 |
except ZeroDivisionError: |
| 950 |
pass |
| 951 |
else: |
| 952 |
raise Exception("ZeroDivisionError not raised") |
| 953 |
""" |
| 954 |
assert_python_ok('-c', code) |
| 955 |
|
| 956 |
@unittest.skipUnless(hasattr(signal, 'pthread_sigmask'), |
| 957 |
'need signal.pthread_sigmask()') |
| 958 |
def wait_helper(self, blocked, test): |
| 959 |
""" |
| 960 |
test: body of the "def test(signum):" function. |
| 961 |
blocked: number of the blocked signal |
| 962 |
""" |
| 963 |
code = '''if 1: |
| 964 |
import signal |
| 965 |
import sys |
| 966 |
from signal import Signals |
| 967 |
|
| 968 |
def handler(signum, frame): |
| 969 |
1/0 |
| 970 |
|
| 971 |
%s |
| 972 |
|
| 973 |
blocked = %s |
| 974 |
signum = signal.SIGALRM |
| 975 |
|
| 976 |
# child: block and wait the signal |
| 977 |
try: |
| 978 |
signal.signal(signum, handler) |
| 979 |
signal.pthread_sigmask(signal.SIG_BLOCK, [blocked]) |
| 980 |
|
| 981 |
# Do the tests |
| 982 |
test(signum) |
| 983 |
|
| 984 |
# The handler must not be called on unblock |
| 985 |
try: |
| 986 |
signal.pthread_sigmask(signal.SIG_UNBLOCK, [blocked]) |
| 987 |
except ZeroDivisionError: |
| 988 |
print("the signal handler has been called", |
| 989 |
file=sys.stderr) |
| 990 |
sys.exit(1) |
| 991 |
except BaseException as err: |
| 992 |
print("error: {}".format(err), file=sys.stderr) |
| 993 |
sys.stderr.flush() |
| 994 |
sys.exit(1) |
| 995 |
''' % (test.strip(), blocked) |
| 996 |
|
| 997 |
|
| 998 |
|
| 999 |
|
| 1000 |
assert_python_ok('-c', code) |
| 1001 |
|
| 1002 |
@unittest.skipUnless(hasattr(signal, 'sigwait'), |
| 1003 |
'need signal.sigwait()') |
| 1004 |
def test_sigwait(self): |
| 1005 |
self.wait_helper(signal.SIGALRM, ''' |
| 1006 |
def test(signum): |
| 1007 |
signal.alarm(1) |
| 1008 |
received = signal.sigwait([signum]) |
| 1009 |
assert isinstance(received, signal.Signals), received |
| 1010 |
if received != signum: |
| 1011 |
raise Exception('received %s, not %s' % (received, signum)) |
| 1012 |
''') |
| 1013 |
|
| 1014 |
@unittest.skipUnless(hasattr(signal, 'sigwaitinfo'), |
| 1015 |
'need signal.sigwaitinfo()') |
| 1016 |
def test_sigwaitinfo(self): |
| 1017 |
self.wait_helper(signal.SIGALRM, ''' |
| 1018 |
def test(signum): |
| 1019 |
signal.alarm(1) |
| 1020 |
info = signal.sigwaitinfo([signum]) |
| 1021 |
if info.si_signo != signum: |
| 1022 |
raise Exception("info.si_signo != %s" % signum) |
| 1023 |
''') |
| 1024 |
|
| 1025 |
@unittest.skipUnless(hasattr(signal, 'sigtimedwait'), |
| 1026 |
'need signal.sigtimedwait()') |
| 1027 |
def test_sigtimedwait(self): |
| 1028 |
self.wait_helper(signal.SIGALRM, ''' |
| 1029 |
def test(signum): |
| 1030 |
signal.alarm(1) |
| 1031 |
info = signal.sigtimedwait([signum], 10.1000) |
| 1032 |
if info.si_signo != signum: |
| 1033 |
raise Exception('info.si_signo != %s' % signum) |
| 1034 |
''') |
| 1035 |
|
| 1036 |
@unittest.skipUnless(hasattr(signal, 'sigtimedwait'), |
| 1037 |
'need signal.sigtimedwait()') |
| 1038 |
def test_sigtimedwait_poll(self): |
| 1039 |
|
| 1040 |
self.wait_helper(signal.SIGALRM, ''' |
| 1041 |
def test(signum): |
| 1042 |
import os |
| 1043 |
os.kill(os.getpid(), signum) |
| 1044 |
info = signal.sigtimedwait([signum], 0) |
| 1045 |
if info.si_signo != signum: |
| 1046 |
raise Exception('info.si_signo != %s' % signum) |
| 1047 |
''') |
| 1048 |
|
| 1049 |
@unittest.skipUnless(hasattr(signal, 'sigtimedwait'), |
| 1050 |
'need signal.sigtimedwait()') |
| 1051 |
def test_sigtimedwait_timeout(self): |
| 1052 |
self.wait_helper(signal.SIGALRM, ''' |
| 1053 |
def test(signum): |
| 1054 |
received = signal.sigtimedwait([signum], 1.0) |
| 1055 |
if received is not None: |
| 1056 |
raise Exception("received=%r" % (received,)) |
| 1057 |
''') |
| 1058 |
|
| 1059 |
@unittest.skipUnless(hasattr(signal, 'sigtimedwait'), |
| 1060 |
'need signal.sigtimedwait()') |
| 1061 |
def test_sigtimedwait_negative_timeout(self): |
| 1062 |
signum = signal.SIGALRM |
| 1063 |
self.assertRaises(ValueError, signal.sigtimedwait, [signum], -1.0) |
| 1064 |
|
| 1065 |
@unittest.skipUnless(hasattr(signal, 'sigwait'), |
| 1066 |
'need signal.sigwait()') |
| 1067 |
@unittest.skipUnless(hasattr(signal, 'pthread_sigmask'), |
| 1068 |
'need signal.pthread_sigmask()') |
| 1069 |
@threading_helper.requires_working_threading() |
| 1070 |
def test_sigwait_thread(self): |
| 1071 |
|
| 1072 |
|
| 1073 |
|
| 1074 |
|
| 1075 |
assert_python_ok("-c", """if True: |
| 1076 |
import os, threading, sys, time, signal |
| 1077 |
|
| 1078 |
# the default handler terminates the process |
| 1079 |
signum = signal.SIGUSR1 |
| 1080 |
|
| 1081 |
def kill_later(): |
| 1082 |
# wait until the main thread is waiting in sigwait() |
| 1083 |
time.sleep(1) |
| 1084 |
os.kill(os.getpid(), signum) |
| 1085 |
|
| 1086 |
# the signal must be blocked by all the threads |
| 1087 |
signal.pthread_sigmask(signal.SIG_BLOCK, [signum]) |
| 1088 |
killer = threading.Thread(target=kill_later) |
| 1089 |
killer.start() |
| 1090 |
received = signal.sigwait([signum]) |
| 1091 |
if received != signum: |
| 1092 |
print("sigwait() received %s, not %s" % (received, signum), |
| 1093 |
file=sys.stderr) |
| 1094 |
sys.exit(1) |
| 1095 |
killer.join() |
| 1096 |
# unblock the signal, which should have been cleared by sigwait() |
| 1097 |
signal.pthread_sigmask(signal.SIG_UNBLOCK, [signum]) |
| 1098 |
""") |
| 1099 |
|
| 1100 |
@unittest.skipUnless(hasattr(signal, 'pthread_sigmask'), |
| 1101 |
'need signal.pthread_sigmask()') |
| 1102 |
def test_pthread_sigmask_arguments(self): |
| 1103 |
self.assertRaises(TypeError, signal.pthread_sigmask) |
| 1104 |
self.assertRaises(TypeError, signal.pthread_sigmask, 1) |
| 1105 |
self.assertRaises(TypeError, signal.pthread_sigmask, 1, 2, 3) |
| 1106 |
self.assertRaises(OSError, signal.pthread_sigmask, 1700, []) |
| 1107 |
with self.assertRaises(ValueError): |
| 1108 |
signal.pthread_sigmask(signal.SIG_BLOCK, [signal.NSIG]) |
| 1109 |
with self.assertRaises(ValueError): |
| 1110 |
signal.pthread_sigmask(signal.SIG_BLOCK, [0]) |
| 1111 |
with self.assertRaises(ValueError): |
| 1112 |
signal.pthread_sigmask(signal.SIG_BLOCK, [1<<1000]) |
| 1113 |
|
| 1114 |
@unittest.skipUnless(hasattr(signal, 'pthread_sigmask'), |
| 1115 |
'need signal.pthread_sigmask()') |
| 1116 |
def test_pthread_sigmask_valid_signals(self): |
| 1117 |
s = signal.pthread_sigmask(signal.SIG_BLOCK, signal.valid_signals()) |
| 1118 |
self.addCleanup(signal.pthread_sigmask, signal.SIG_SETMASK, s) |
| 1119 |
|
| 1120 |
s = signal.pthread_sigmask(signal.SIG_UNBLOCK, signal.valid_signals()) |
| 1121 |
self.assertLessEqual(s, signal.valid_signals()) |
| 1122 |
|
| 1123 |
@unittest.skipUnless(hasattr(signal, 'pthread_sigmask'), |
| 1124 |
'need signal.pthread_sigmask()') |
| 1125 |
@threading_helper.requires_working_threading() |
| 1126 |
def test_pthread_sigmask(self): |
| 1127 |
code = """if 1: |
| 1128 |
import signal |
| 1129 |
import os; import threading |
| 1130 |
|
| 1131 |
def handler(signum, frame): |
| 1132 |
1/0 |
| 1133 |
|
| 1134 |
def kill(signum): |
| 1135 |
os.kill(os.getpid(), signum) |
| 1136 |
|
| 1137 |
def check_mask(mask): |
| 1138 |
for sig in mask: |
| 1139 |
assert isinstance(sig, signal.Signals), repr(sig) |
| 1140 |
|
| 1141 |
def read_sigmask(): |
| 1142 |
sigmask = signal.pthread_sigmask(signal.SIG_BLOCK, []) |
| 1143 |
check_mask(sigmask) |
| 1144 |
return sigmask |
| 1145 |
|
| 1146 |
signum = signal.SIGUSR1 |
| 1147 |
|
| 1148 |
# Install our signal handler |
| 1149 |
old_handler = signal.signal(signum, handler) |
| 1150 |
|
| 1151 |
# Unblock SIGUSR1 (and copy the old mask) to test our signal handler |
| 1152 |
old_mask = signal.pthread_sigmask(signal.SIG_UNBLOCK, [signum]) |
| 1153 |
check_mask(old_mask) |
| 1154 |
try: |
| 1155 |
kill(signum) |
| 1156 |
except ZeroDivisionError: |
| 1157 |
pass |
| 1158 |
else: |
| 1159 |
raise Exception("ZeroDivisionError not raised") |
| 1160 |
|
| 1161 |
# Block and then raise SIGUSR1. The signal is blocked: the signal |
| 1162 |
# handler is not called, and the signal is now pending |
| 1163 |
mask = signal.pthread_sigmask(signal.SIG_BLOCK, [signum]) |
| 1164 |
check_mask(mask) |
| 1165 |
kill(signum) |
| 1166 |
|
| 1167 |
# Check the new mask |
| 1168 |
blocked = read_sigmask() |
| 1169 |
check_mask(blocked) |
| 1170 |
if signum not in blocked: |
| 1171 |
raise Exception("%s not in %s" % (signum, blocked)) |
| 1172 |
if old_mask ^ blocked != {signum}: |
| 1173 |
raise Exception("%s ^ %s != {%s}" % (old_mask, blocked, signum)) |
| 1174 |
|
| 1175 |
# Unblock SIGUSR1 |
| 1176 |
try: |
| 1177 |
# unblock the pending signal calls immediately the signal handler |
| 1178 |
signal.pthread_sigmask(signal.SIG_UNBLOCK, [signum]) |
| 1179 |
except ZeroDivisionError: |
| 1180 |
pass |
| 1181 |
else: |
| 1182 |
raise Exception("ZeroDivisionError not raised") |
| 1183 |
try: |
| 1184 |
kill(signum) |
| 1185 |
except ZeroDivisionError: |
| 1186 |
pass |
| 1187 |
else: |
| 1188 |
raise Exception("ZeroDivisionError not raised") |
| 1189 |
|
| 1190 |
# Check the new mask |
| 1191 |
unblocked = read_sigmask() |
| 1192 |
if signum in unblocked: |
| 1193 |
raise Exception("%s in %s" % (signum, unblocked)) |
| 1194 |
if blocked ^ unblocked != {signum}: |
| 1195 |
raise Exception("%s ^ %s != {%s}" % (blocked, unblocked, signum)) |
| 1196 |
if old_mask != unblocked: |
| 1197 |
raise Exception("%s != %s" % (old_mask, unblocked)) |
| 1198 |
""" |
| 1199 |
assert_python_ok('-c', code) |
| 1200 |
|
| 1201 |
@unittest.skipUnless(hasattr(signal, 'pthread_kill'), |
| 1202 |
'need signal.pthread_kill()') |
| 1203 |
@threading_helper.requires_working_threading() |
| 1204 |
def test_pthread_kill_main_thread(self): |
| 1205 |
|
| 1206 |
|
| 1207 |
code = """if True: |
| 1208 |
import threading |
| 1209 |
import signal |
| 1210 |
import sys |
| 1211 |
|
| 1212 |
def handler(signum, frame): |
| 1213 |
sys.exit(3) |
| 1214 |
|
| 1215 |
signal.signal(signal.SIGUSR1, handler) |
| 1216 |
signal.pthread_kill(threading.get_ident(), signal.SIGUSR1) |
| 1217 |
sys.exit(2) |
| 1218 |
""" |
| 1219 |
|
| 1220 |
with spawn_python('-c', code) as process: |
| 1221 |
stdout, stderr = process.communicate() |
| 1222 |
exitcode = process.wait() |
| 1223 |
if exitcode != 3: |
| 1224 |
raise Exception("Child error (exit code %s): %s" % |
| 1225 |
(exitcode, stdout)) |
| 1226 |
|
| 1227 |
|
| 1228 |
class StressTest(unittest.TestCase): |
| 1229 |
""" |
| 1230 |
Stress signal delivery, especially when a signal arrives in |
| 1231 |
the middle of recomputing the signal state or executing |
| 1232 |
previously tripped signal handlers. |
| 1233 |
""" |
| 1234 |
|
| 1235 |
def setsig(self, signum, handler): |
| 1236 |
old_handler = signal.signal(signum, handler) |
| 1237 |
self.addCleanup(signal.signal, signum, old_handler) |
| 1238 |
|
| 1239 |
def measure_itimer_resolution(self): |
| 1240 |
N = 20 |
| 1241 |
times = [] |
| 1242 |
|
| 1243 |
def handler(signum=None, frame=None): |
| 1244 |
if len(times) < N: |
| 1245 |
times.append(time.perf_counter()) |
| 1246 |
, |
| 1247 |
|
| 1248 |
|
| 1249 |
signal.setitimer(signal.ITIMER_REAL, 1e-6) |
| 1250 |
|
| 1251 |
self.addCleanup(signal.setitimer, signal.ITIMER_REAL, 0) |
| 1252 |
self.setsig(signal.SIGALRM, handler) |
| 1253 |
handler() |
| 1254 |
while len(times) < N: |
| 1255 |
time.sleep(1e-3) |
| 1256 |
|
| 1257 |
durations = [times[i+1] - times[i] for i in range(len(times) - 1)] |
| 1258 |
med = statistics.median(durations) |
| 1259 |
if support.verbose: |
| 1260 |
print("detected median itimer() resolution: %.6f s." % (med,)) |
| 1261 |
return med |
| 1262 |
|
| 1263 |
def decide_itimer_count(self): |
| 1264 |
|
| 1265 |
|
| 1266 |
|
| 1267 |
reso = self.measure_itimer_resolution() |
| 1268 |
if reso <= 1e-4: |
| 1269 |
return 10000 |
| 1270 |
elif reso <= 1e-2: |
| 1271 |
return 100 |
| 1272 |
else: |
| 1273 |
self.skipTest("detected itimer resolution (%.3f s.) too high " |
| 1274 |
"(> 10 ms.) on this platform (or system too busy)" |
| 1275 |
% (reso,)) |
| 1276 |
|
| 1277 |
@unittest.skipUnless(hasattr(signal, "setitimer"), |
| 1278 |
"test needs setitimer()") |
| 1279 |
def test_stress_delivery_dependent(self): |
| 1280 |
""" |
| 1281 |
This test uses dependent signal handlers. |
| 1282 |
""" |
| 1283 |
N = self.decide_itimer_count() |
| 1284 |
sigs = [] |
| 1285 |
|
| 1286 |
def first_handler(signum, frame): |
| 1287 |
|
| 1288 |
|
| 1289 |
|
| 1290 |
|
| 1291 |
|
| 1292 |
signal.setitimer(signal.ITIMER_REAL, 1e-6 + random.random() * 1e-5) |
| 1293 |
|
| 1294 |
def second_handler(signum=None, frame=None): |
| 1295 |
sigs.append(signum) |
| 1296 |
|
| 1297 |
|
| 1298 |
|
| 1299 |
|
| 1300 |
self.setsig(signal.SIGPROF, first_handler) |
| 1301 |
self.setsig(signal.SIGUSR1, first_handler) |
| 1302 |
self.setsig(signal.SIGALRM, second_handler) |
| 1303 |
|
| 1304 |
expected_sigs = 0 |
| 1305 |
deadline = time.monotonic() + support.SHORT_TIMEOUT |
| 1306 |
|
| 1307 |
while expected_sigs < N: |
| 1308 |
os.kill(os.getpid(), signal.SIGPROF) |
| 1309 |
expected_sigs += 1 |
| 1310 |
|
| 1311 |
while len(sigs) < expected_sigs and time.monotonic() < deadline: |
| 1312 |
time.sleep(1e-5) |
| 1313 |
|
| 1314 |
os.kill(os.getpid(), signal.SIGUSR1) |
| 1315 |
expected_sigs += 1 |
| 1316 |
while len(sigs) < expected_sigs and time.monotonic() < deadline: |
| 1317 |
time.sleep(1e-5) |
| 1318 |
|
| 1319 |
|
| 1320 |
|
| 1321 |
self.assertEqual(len(sigs), N, "Some signals were lost") |
| 1322 |
|
| 1323 |
@unittest.skipUnless(hasattr(signal, "setitimer"), |
| 1324 |
"test needs setitimer()") |
| 1325 |
def test_stress_delivery_simultaneous(self): |
| 1326 |
""" |
| 1327 |
This test uses simultaneous signal handlers. |
| 1328 |
""" |
| 1329 |
N = self.decide_itimer_count() |
| 1330 |
sigs = [] |
| 1331 |
|
| 1332 |
def handler(signum, frame): |
| 1333 |
sigs.append(signum) |
| 1334 |
|
| 1335 |
self.setsig(signal.SIGUSR1, handler) |
| 1336 |
self.setsig(signal.SIGALRM, handler) |
| 1337 |
|
| 1338 |
expected_sigs = 0 |
| 1339 |
while expected_sigs < N: |
| 1340 |
|
| 1341 |
|
| 1342 |
signal.setitimer(signal.ITIMER_REAL, 1e-6 + random.random() * 1e-5) |
| 1343 |
os.kill(os.getpid(), signal.SIGUSR1) |
| 1344 |
|
| 1345 |
expected_sigs += 2 |
| 1346 |
|
| 1347 |
for _ in support.sleeping_retry(support.SHORT_TIMEOUT, error=False): |
| 1348 |
if len(sigs) >= expected_sigs: |
| 1349 |
break |
| 1350 |
|
| 1351 |
|
| 1352 |
|
| 1353 |
self.assertEqual(len(sigs), N, "Some signals were lost") |
| 1354 |
|
| 1355 |
@unittest.skipIf(sys.platform == "darwin", "crashes due to system bug (FB13453490)") |
| 1356 |
@unittest.skipUnless(hasattr(signal, "SIGUSR1"), |
| 1357 |
"test needs SIGUSR1") |
| 1358 |
@threading_helper.requires_working_threading() |
| 1359 |
def test_stress_modifying_handlers(self): |
| 1360 |
|
| 1361 |
signum = signal.SIGUSR1 |
| 1362 |
num_sent_signals = 0 |
| 1363 |
num_received_signals = 0 |
| 1364 |
do_stop = False |
| 1365 |
|
| 1366 |
def custom_handler(signum, frame): |
| 1367 |
nonlocal num_received_signals |
| 1368 |
num_received_signals += 1 |
| 1369 |
|
| 1370 |
def set_interrupts(): |
| 1371 |
nonlocal num_sent_signals |
| 1372 |
while not do_stop: |
| 1373 |
signal.raise_signal(signum) |
| 1374 |
num_sent_signals += 1 |
| 1375 |
|
| 1376 |
def cycle_handlers(): |
| 1377 |
while num_sent_signals < 100 or num_received_signals < 1: |
| 1378 |
for i in range(20000): |
| 1379 |
|
| 1380 |
for handler in [custom_handler, signal.SIG_IGN]: |
| 1381 |
signal.signal(signum, handler) |
| 1382 |
|
| 1383 |
old_handler = signal.signal(signum, custom_handler) |
| 1384 |
self.addCleanup(signal.signal, signum, old_handler) |
| 1385 |
|
| 1386 |
t = threading.Thread(target=set_interrupts) |
| 1387 |
try: |
| 1388 |
ignored = False |
| 1389 |
with support.catch_unraisable_exception() as cm: |
| 1390 |
t.start() |
| 1391 |
cycle_handlers() |
| 1392 |
do_stop = True |
| 1393 |
t.join() |
| 1394 |
|
| 1395 |
if cm.unraisable is not None: |
| 1396 |
|
| 1397 |
|
| 1398 |
|
| 1399 |
self.assertIsInstance(cm.unraisable.exc_value, OSError) |
| 1400 |
self.assertIn( |
| 1401 |
f"Signal {signum:d} ignored due to race condition", |
| 1402 |
str(cm.unraisable.exc_value)) |
| 1403 |
ignored = True |
| 1404 |
|
| 1405 |
|
| 1406 |
|
| 1407 |
if not ignored: |
| 1408 |
|
| 1409 |
self.assertGreater(num_received_signals, 0) |
| 1410 |
self.assertLessEqual(num_received_signals, num_sent_signals) |
| 1411 |
finally: |
| 1412 |
do_stop = True |
| 1413 |
t.join() |
| 1414 |
|
| 1415 |
|
| 1416 |
class RaiseSignalTest(unittest.TestCase): |
| 1417 |
|
| 1418 |
def test_sigint(self): |
| 1419 |
with self.assertRaises(KeyboardInterrupt): |
| 1420 |
signal.raise_signal(signal.SIGINT) |
| 1421 |
|
| 1422 |
@unittest.skipIf(sys.platform != "win32", "Windows specific test") |
| 1423 |
def test_invalid_argument(self): |
| 1424 |
try: |
| 1425 |
SIGHUP = 1 |
| 1426 |
signal.raise_signal(SIGHUP) |
| 1427 |
self.fail("OSError (Invalid argument) expected") |
| 1428 |
except OSError as e: |
| 1429 |
if e.errno == errno.EINVAL: |
| 1430 |
pass |
| 1431 |
else: |
| 1432 |
raise |
| 1433 |
|
| 1434 |
def test_handler(self): |
| 1435 |
is_ok = False |
| 1436 |
def handler(a, b): |
| 1437 |
nonlocal is_ok |
| 1438 |
is_ok = True |
| 1439 |
old_signal = signal.signal(signal.SIGINT, handler) |
| 1440 |
self.addCleanup(signal.signal, signal.SIGINT, old_signal) |
| 1441 |
|
| 1442 |
signal.raise_signal(signal.SIGINT) |
| 1443 |
self.assertTrue(is_ok) |
| 1444 |
|
| 1445 |
@cpython_only |
| 1446 |
def test__thread_interrupt_main(self): |
| 1447 |
|
| 1448 |
code = """if 1: |
| 1449 |
import _thread |
| 1450 |
class Foo(): |
| 1451 |
def __del__(self): |
| 1452 |
_thread.interrupt_main() |
| 1453 |
|
| 1454 |
x = Foo() |
| 1455 |
""" |
| 1456 |
|
| 1457 |
rc, out, err = assert_python_ok('-c', code) |
| 1458 |
self.assertIn(b'OSError: Signal 2 ignored due to race condition', err) |
| 1459 |
|
| 1460 |
|
| 1461 |
|
| 1462 |
class PidfdSignalTest(unittest.TestCase): |
| 1463 |
|
| 1464 |
@unittest.skipUnless( |
| 1465 |
hasattr(signal, "pidfd_send_signal"), |
| 1466 |
"pidfd support not built in", |
| 1467 |
) |
| 1468 |
def test_pidfd_send_signal(self): |
| 1469 |
with self.assertRaises(OSError) as cm: |
| 1470 |
signal.pidfd_send_signal(0, signal.SIGINT) |
| 1471 |
if cm.exception.errno == errno.ENOSYS: |
| 1472 |
self.skipTest("kernel does not support pidfds") |
| 1473 |
elif cm.exception.errno == errno.EPERM: |
| 1474 |
self.skipTest("Not enough privileges to use pidfs") |
| 1475 |
self.assertEqual(cm.exception.errno, errno.EBADF) |
| 1476 |
my_pidfd = os.open(f'/proc/{os.getpid()}', os.O_DIRECTORY) |
| 1477 |
self.addCleanup(os.close, my_pidfd) |
| 1478 |
with self.assertRaisesRegex(TypeError, "^siginfo must be None$"): |
| 1479 |
signal.pidfd_send_signal(my_pidfd, signal.SIGINT, object(), 0) |
| 1480 |
with self.assertRaises(KeyboardInterrupt): |
| 1481 |
signal.pidfd_send_signal(my_pidfd, signal.SIGINT) |
| 1482 |
|
| 1483 |
def tearDownModule(): |
| 1484 |
support.reap_children() |
| 1485 |
|
| 1486 |
if __name__ == "__main__": |
| 1487 |
unittest.main() |