| 1 |
"""Tests for unix_events.py.""" |
| 2 |
|
| 3 |
import contextlib |
| 4 |
import errno |
| 5 |
import io |
| 6 |
import multiprocessing |
| 7 |
from multiprocessing.util import _cleanup_tests as multiprocessing_cleanup_tests |
| 8 |
import os |
| 9 |
import signal |
| 10 |
import socket |
| 11 |
import stat |
| 12 |
import sys |
| 13 |
import threading |
| 14 |
import time |
| 15 |
import unittest |
| 16 |
from unittest import mock |
| 17 |
import warnings |
| 18 |
|
| 19 |
from test import support |
| 20 |
from test.support import os_helper |
| 21 |
from test.support import socket_helper |
| 22 |
from test.support import wait_process |
| 23 |
from test.support import hashlib_helper |
| 24 |
|
| 25 |
if sys.platform == 'win32': |
| 26 |
raise unittest.SkipTest('UNIX only') |
| 27 |
|
| 28 |
|
| 29 |
import asyncio |
| 30 |
from asyncio import log |
| 31 |
from asyncio import unix_events |
| 32 |
from test.test_asyncio import utils as test_utils |
| 33 |
|
| 34 |
|
| 35 |
def tearDownModule(): |
| 36 |
asyncio.set_event_loop_policy(None) |
| 37 |
|
| 38 |
|
| 39 |
MOCK_ANY = mock.ANY |
| 40 |
|
| 41 |
|
| 42 |
def EXITCODE(exitcode): |
| 43 |
return 32768 + exitcode |
| 44 |
|
| 45 |
|
| 46 |
def SIGNAL(signum): |
| 47 |
if not 1 <= signum <= 68: |
| 48 |
raise AssertionError(f'invalid signum {signum}') |
| 49 |
return 32768 - signum |
| 50 |
|
| 51 |
|
| 52 |
def close_pipe_transport(transport): |
| 53 |
# Don't call transport.close() because the event loop and the selector |
| 54 |
# are mocked |
| 55 |
if transport._pipe is None: |
| 56 |
return |
| 57 |
transport._pipe.close() |
| 58 |
transport._pipe = None |
| 59 |
|
| 60 |
|
| 61 |
@unittest.skipUnless(signal, 'Signals are not supported') |
| 62 |
class SelectorEventLoopSignalTests(test_utils.TestCase): |
| 63 |
|
| 64 |
def setUp(self): |
| 65 |
super().setUp() |
| 66 |
self.loop = asyncio.SelectorEventLoop() |
| 67 |
self.set_event_loop(self.loop) |
| 68 |
|
| 69 |
def test_check_signal(self): |
| 70 |
self.assertRaises( |
| 71 |
TypeError, self.loop._check_signal, '1') |
| 72 |
self.assertRaises( |
| 73 |
ValueError, self.loop._check_signal, signal.NSIG + 1) |
| 74 |
|
| 75 |
def test_handle_signal_no_handler(self): |
| 76 |
self.loop._handle_signal(signal.NSIG + 1) |
| 77 |
|
| 78 |
def test_handle_signal_cancelled_handler(self): |
| 79 |
h = asyncio.Handle(mock.Mock(), (), |
| 80 |
loop=mock.Mock()) |
| 81 |
h.cancel() |
| 82 |
self.loop._signal_handlers[signal.NSIG + 1] = h |
| 83 |
self.loop.remove_signal_handler = mock.Mock() |
| 84 |
self.loop._handle_signal(signal.NSIG + 1) |
| 85 |
self.loop.remove_signal_handler.assert_called_with(signal.NSIG + 1) |
| 86 |
|
| 87 |
@mock.patch('asyncio.unix_events.signal') |
| 88 |
def test_add_signal_handler_setup_error(self, m_signal): |
| 89 |
m_signal.NSIG = signal.NSIG |
| 90 |
m_signal.valid_signals = signal.valid_signals |
| 91 |
m_signal.set_wakeup_fd.side_effect = ValueError |
| 92 |
|
| 93 |
self.assertRaises( |
| 94 |
RuntimeError, |
| 95 |
self.loop.add_signal_handler, |
| 96 |
signal.SIGINT, lambda: True) |
| 97 |
|
| 98 |
@mock.patch('asyncio.unix_events.signal') |
| 99 |
def test_add_signal_handler_coroutine_error(self, m_signal): |
| 100 |
m_signal.NSIG = signal.NSIG |
| 101 |
|
| 102 |
async def simple_coroutine(): |
| 103 |
pass |
| 104 |
|
| 105 |
# callback must not be a coroutine function |
| 106 |
coro_func = simple_coroutine |
| 107 |
coro_obj = coro_func() |
| 108 |
self.addCleanup(coro_obj.close) |
| 109 |
for func in (coro_func, coro_obj): |
| 110 |
self.assertRaisesRegex( |
| 111 |
TypeError, 'coroutines cannot be used with add_signal_handler', |
| 112 |
self.loop.add_signal_handler, |
| 113 |
signal.SIGINT, func) |
| 114 |
|
| 115 |
@mock.patch('asyncio.unix_events.signal') |
| 116 |
def test_add_signal_handler(self, m_signal): |
| 117 |
m_signal.NSIG = signal.NSIG |
| 118 |
m_signal.valid_signals = signal.valid_signals |
| 119 |
|
| 120 |
cb = lambda: True |
| 121 |
self.loop.add_signal_handler(signal.SIGHUP, cb) |
| 122 |
h = self.loop._signal_handlers.get(signal.SIGHUP) |
| 123 |
self.assertIsInstance(h, asyncio.Handle) |
| 124 |
self.assertEqual(h._callback, cb) |
| 125 |
|
| 126 |
@mock.patch('asyncio.unix_events.signal') |
| 127 |
def test_add_signal_handler_install_error(self, m_signal): |
| 128 |
m_signal.NSIG = signal.NSIG |
| 129 |
m_signal.valid_signals = signal.valid_signals |
| 130 |
|
| 131 |
def set_wakeup_fd(fd): |
| 132 |
if fd == -1: |
| 133 |
raise ValueError() |
| 134 |
m_signal.set_wakeup_fd = set_wakeup_fd |
| 135 |
|
| 136 |
class Err(OSError): |
| 137 |
errno = errno.EFAULT |
| 138 |
m_signal.signal.side_effect = Err |
| 139 |
|
| 140 |
self.assertRaises( |
| 141 |
Err, |
| 142 |
self.loop.add_signal_handler, |
| 143 |
signal.SIGINT, lambda: True) |
| 144 |
|
| 145 |
@mock.patch('asyncio.unix_events.signal') |
| 146 |
@mock.patch('asyncio.base_events.logger') |
| 147 |
def test_add_signal_handler_install_error2(self, m_logging, m_signal): |
| 148 |
m_signal.NSIG = signal.NSIG |
| 149 |
m_signal.valid_signals = signal.valid_signals |
| 150 |
|
| 151 |
class Err(OSError): |
| 152 |
errno = errno.EINVAL |
| 153 |
m_signal.signal.side_effect = Err |
| 154 |
|
| 155 |
self.loop._signal_handlers[signal.SIGHUP] = lambda: True |
| 156 |
self.assertRaises( |
| 157 |
RuntimeError, |
| 158 |
self.loop.add_signal_handler, |
| 159 |
signal.SIGINT, lambda: True) |
| 160 |
self.assertFalse(m_logging.info.called) |
| 161 |
self.assertEqual(1, m_signal.set_wakeup_fd.call_count) |
| 162 |
|
| 163 |
@mock.patch('asyncio.unix_events.signal') |
| 164 |
@mock.patch('asyncio.base_events.logger') |
| 165 |
def test_add_signal_handler_install_error3(self, m_logging, m_signal): |
| 166 |
class Err(OSError): |
| 167 |
errno = errno.EINVAL |
| 168 |
m_signal.signal.side_effect = Err |
| 169 |
m_signal.NSIG = signal.NSIG |
| 170 |
m_signal.valid_signals = signal.valid_signals |
| 171 |
|
| 172 |
self.assertRaises( |
| 173 |
RuntimeError, |
| 174 |
self.loop.add_signal_handler, |
| 175 |
signal.SIGINT, lambda: True) |
| 176 |
self.assertFalse(m_logging.info.called) |
| 177 |
self.assertEqual(2, m_signal.set_wakeup_fd.call_count) |
| 178 |
|
| 179 |
@mock.patch('asyncio.unix_events.signal') |
| 180 |
def test_remove_signal_handler(self, m_signal): |
| 181 |
m_signal.NSIG = signal.NSIG |
| 182 |
m_signal.valid_signals = signal.valid_signals |
| 183 |
|
| 184 |
self.loop.add_signal_handler(signal.SIGHUP, lambda: True) |
| 185 |
|
| 186 |
self.assertTrue( |
| 187 |
self.loop.remove_signal_handler(signal.SIGHUP)) |
| 188 |
self.assertTrue(m_signal.set_wakeup_fd.called) |
| 189 |
self.assertTrue(m_signal.signal.called) |
| 190 |
self.assertEqual( |
| 191 |
(signal.SIGHUP, m_signal.SIG_DFL), m_signal.signal.call_args[0]) |
| 192 |
|
| 193 |
@mock.patch('asyncio.unix_events.signal') |
| 194 |
def test_remove_signal_handler_2(self, m_signal): |
| 195 |
m_signal.NSIG = signal.NSIG |
| 196 |
m_signal.SIGINT = signal.SIGINT |
| 197 |
m_signal.valid_signals = signal.valid_signals |
| 198 |
|
| 199 |
self.loop.add_signal_handler(signal.SIGINT, lambda: True) |
| 200 |
self.loop._signal_handlers[signal.SIGHUP] = object() |
| 201 |
m_signal.set_wakeup_fd.reset_mock() |
| 202 |
|
| 203 |
self.assertTrue( |
| 204 |
self.loop.remove_signal_handler(signal.SIGINT)) |
| 205 |
self.assertFalse(m_signal.set_wakeup_fd.called) |
| 206 |
self.assertTrue(m_signal.signal.called) |
| 207 |
self.assertEqual( |
| 208 |
(signal.SIGINT, m_signal.default_int_handler), |
| 209 |
m_signal.signal.call_args[0]) |
| 210 |
|
| 211 |
@mock.patch('asyncio.unix_events.signal') |
| 212 |
@mock.patch('asyncio.base_events.logger') |
| 213 |
def test_remove_signal_handler_cleanup_error(self, m_logging, m_signal): |
| 214 |
m_signal.NSIG = signal.NSIG |
| 215 |
m_signal.valid_signals = signal.valid_signals |
| 216 |
self.loop.add_signal_handler(signal.SIGHUP, lambda: True) |
| 217 |
|
| 218 |
m_signal.set_wakeup_fd.side_effect = ValueError |
| 219 |
|
| 220 |
self.loop.remove_signal_handler(signal.SIGHUP) |
| 221 |
self.assertTrue(m_logging.info) |
| 222 |
|
| 223 |
@mock.patch('asyncio.unix_events.signal') |
| 224 |
def test_remove_signal_handler_error(self, m_signal): |
| 225 |
m_signal.NSIG = signal.NSIG |
| 226 |
m_signal.valid_signals = signal.valid_signals |
| 227 |
self.loop.add_signal_handler(signal.SIGHUP, lambda: True) |
| 228 |
|
| 229 |
m_signal.signal.side_effect = OSError |
| 230 |
|
| 231 |
self.assertRaises( |
| 232 |
OSError, self.loop.remove_signal_handler, signal.SIGHUP) |
| 233 |
|
| 234 |
@mock.patch('asyncio.unix_events.signal') |
| 235 |
def test_remove_signal_handler_error2(self, m_signal): |
| 236 |
m_signal.NSIG = signal.NSIG |
| 237 |
m_signal.valid_signals = signal.valid_signals |
| 238 |
self.loop.add_signal_handler(signal.SIGHUP, lambda: True) |
| 239 |
|
| 240 |
class Err(OSError): |
| 241 |
errno = errno.EINVAL |
| 242 |
m_signal.signal.side_effect = Err |
| 243 |
|
| 244 |
self.assertRaises( |
| 245 |
RuntimeError, self.loop.remove_signal_handler, signal.SIGHUP) |
| 246 |
|
| 247 |
@mock.patch('asyncio.unix_events.signal') |
| 248 |
def test_close(self, m_signal): |
| 249 |
m_signal.NSIG = signal.NSIG |
| 250 |
m_signal.valid_signals = signal.valid_signals |
| 251 |
|
| 252 |
self.loop.add_signal_handler(signal.SIGHUP, lambda: True) |
| 253 |
self.loop.add_signal_handler(signal.SIGCHLD, lambda: True) |
| 254 |
|
| 255 |
self.assertEqual(len(self.loop._signal_handlers), 2) |
| 256 |
|
| 257 |
m_signal.set_wakeup_fd.reset_mock() |
| 258 |
|
| 259 |
self.loop.close() |
| 260 |
|
| 261 |
self.assertEqual(len(self.loop._signal_handlers), 0) |
| 262 |
m_signal.set_wakeup_fd.assert_called_once_with(-1) |
| 263 |
|
| 264 |
@mock.patch('asyncio.unix_events.sys') |
| 265 |
@mock.patch('asyncio.unix_events.signal') |
| 266 |
def test_close_on_finalizing(self, m_signal, m_sys): |
| 267 |
m_signal.NSIG = signal.NSIG |
| 268 |
m_signal.valid_signals = signal.valid_signals |
| 269 |
self.loop.add_signal_handler(signal.SIGHUP, lambda: True) |
| 270 |
|
| 271 |
self.assertEqual(len(self.loop._signal_handlers), 1) |
| 272 |
m_sys.is_finalizing.return_value = True |
| 273 |
m_signal.signal.reset_mock() |
| 274 |
|
| 275 |
with self.assertWarnsRegex(ResourceWarning, |
| 276 |
"skipping signal handlers removal"): |
| 277 |
self.loop.close() |
| 278 |
|
| 279 |
self.assertEqual(len(self.loop._signal_handlers), 0) |
| 280 |
self.assertFalse(m_signal.signal.called) |
| 281 |
|
| 282 |
|
| 283 |
@unittest.skipUnless(hasattr(socket, 'AF_UNIX'), |
| 284 |
'UNIX Sockets are not supported') |
| 285 |
class SelectorEventLoopUnixSocketTests(test_utils.TestCase): |
| 286 |
|
| 287 |
def setUp(self): |
| 288 |
super().setUp() |
| 289 |
self.loop = asyncio.SelectorEventLoop() |
| 290 |
self.set_event_loop(self.loop) |
| 291 |
|
| 292 |
@socket_helper.skip_unless_bind_unix_socket |
| 293 |
def test_create_unix_server_existing_path_sock(self): |
| 294 |
with test_utils.unix_socket_path() as path: |
| 295 |
sock = socket.socket(socket.AF_UNIX) |
| 296 |
sock.bind(path) |
| 297 |
sock.listen(1) |
| 298 |
sock.close() |
| 299 |
|
| 300 |
coro = self.loop.create_unix_server(lambda: None, path) |
| 301 |
srv = self.loop.run_until_complete(coro) |
| 302 |
srv.close() |
| 303 |
self.loop.run_until_complete(srv.wait_closed()) |
| 304 |
|
| 305 |
@socket_helper.skip_unless_bind_unix_socket |
| 306 |
def test_create_unix_server_pathlike(self): |
| 307 |
with test_utils.unix_socket_path() as path: |
| 308 |
path = os_helper.FakePath(path) |
| 309 |
srv_coro = self.loop.create_unix_server(lambda: None, path) |
| 310 |
srv = self.loop.run_until_complete(srv_coro) |
| 311 |
srv.close() |
| 312 |
self.loop.run_until_complete(srv.wait_closed()) |
| 313 |
|
| 314 |
def test_create_unix_connection_pathlike(self): |
| 315 |
with test_utils.unix_socket_path() as path: |
| 316 |
path = os_helper.FakePath(path) |
| 317 |
coro = self.loop.create_unix_connection(lambda: None, path) |
| 318 |
with self.assertRaises(FileNotFoundError): |
| 319 |
# If path-like object weren't supported, the exception would be |
| 320 |
# different. |
| 321 |
self.loop.run_until_complete(coro) |
| 322 |
|
| 323 |
def test_create_unix_server_existing_path_nonsock(self): |
| 324 |
path = test_utils.gen_unix_socket_path() |
| 325 |
self.addCleanup(os_helper.unlink, path) |
| 326 |
# create the file |
| 327 |
open(path, "wb").close() |
| 328 |
|
| 329 |
coro = self.loop.create_unix_server(lambda: None, path) |
| 330 |
with self.assertRaisesRegex(OSError, |
| 331 |
'Address.*is already in use'): |
| 332 |
self.loop.run_until_complete(coro) |
| 333 |
|
| 334 |
def test_create_unix_server_ssl_bool(self): |
| 335 |
coro = self.loop.create_unix_server(lambda: None, path='spam', |
| 336 |
ssl=True) |
| 337 |
with self.assertRaisesRegex(TypeError, |
| 338 |
'ssl argument must be an SSLContext'): |
| 339 |
self.loop.run_until_complete(coro) |
| 340 |
|
| 341 |
def test_create_unix_server_nopath_nosock(self): |
| 342 |
coro = self.loop.create_unix_server(lambda: None, path=None) |
| 343 |
with self.assertRaisesRegex(ValueError, |
| 344 |
'path was not specified, and no sock'): |
| 345 |
self.loop.run_until_complete(coro) |
| 346 |
|
| 347 |
def test_create_unix_server_path_inetsock(self): |
| 348 |
sock = socket.socket() |
| 349 |
with sock: |
| 350 |
coro = self.loop.create_unix_server(lambda: None, path=None, |
| 351 |
sock=sock) |
| 352 |
with self.assertRaisesRegex(ValueError, |
| 353 |
'A UNIX Domain Stream.*was expected'): |
| 354 |
self.loop.run_until_complete(coro) |
| 355 |
|
| 356 |
def test_create_unix_server_path_dgram(self): |
| 357 |
sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) |
| 358 |
with sock: |
| 359 |
coro = self.loop.create_unix_server(lambda: None, path=None, |
| 360 |
sock=sock) |
| 361 |
with self.assertRaisesRegex(ValueError, |
| 362 |
'A UNIX Domain Stream.*was expected'): |
| 363 |
self.loop.run_until_complete(coro) |
| 364 |
|
| 365 |
@unittest.skipUnless(hasattr(socket, 'SOCK_NONBLOCK'), |
| 366 |
'no socket.SOCK_NONBLOCK (linux only)') |
| 367 |
@socket_helper.skip_unless_bind_unix_socket |
| 368 |
def test_create_unix_server_path_stream_bittype(self): |
| 369 |
fn = test_utils.gen_unix_socket_path() |
| 370 |
self.addCleanup(os_helper.unlink, fn) |
| 371 |
|
| 372 |
sock = socket.socket(socket.AF_UNIX, |
| 373 |
socket.SOCK_STREAM | socket.SOCK_NONBLOCK) |
| 374 |
with sock: |
| 375 |
sock.bind(fn) |
| 376 |
coro = self.loop.create_unix_server(lambda: None, path=None, |
| 377 |
sock=sock) |
| 378 |
srv = self.loop.run_until_complete(coro) |
| 379 |
srv.close() |
| 380 |
self.loop.run_until_complete(srv.wait_closed()) |
| 381 |
|
| 382 |
def test_create_unix_server_ssl_timeout_with_plain_sock(self): |
| 383 |
coro = self.loop.create_unix_server(lambda: None, path='spam', |
| 384 |
ssl_handshake_timeout=1) |
| 385 |
with self.assertRaisesRegex( |
| 386 |
ValueError, |
| 387 |
'ssl_handshake_timeout is only meaningful with ssl'): |
| 388 |
self.loop.run_until_complete(coro) |
| 389 |
|
| 390 |
def test_create_unix_connection_path_inetsock(self): |
| 391 |
sock = socket.socket() |
| 392 |
with sock: |
| 393 |
coro = self.loop.create_unix_connection(lambda: None, |
| 394 |
sock=sock) |
| 395 |
with self.assertRaisesRegex(ValueError, |
| 396 |
'A UNIX Domain Stream.*was expected'): |
| 397 |
self.loop.run_until_complete(coro) |
| 398 |
|
| 399 |
@mock.patch('asyncio.unix_events.socket') |
| 400 |
def test_create_unix_server_bind_error(self, m_socket): |
| 401 |
# Ensure that the socket is closed on any bind error |
| 402 |
sock = mock.Mock() |
| 403 |
m_socket.socket.return_value = sock |
| 404 |
|
| 405 |
sock.bind.side_effect = OSError |
| 406 |
coro = self.loop.create_unix_server(lambda: None, path="/test") |
| 407 |
with self.assertRaises(OSError): |
| 408 |
self.loop.run_until_complete(coro) |
| 409 |
self.assertTrue(sock.close.called) |
| 410 |
|
| 411 |
sock.bind.side_effect = MemoryError |
| 412 |
coro = self.loop.create_unix_server(lambda: None, path="/test") |
| 413 |
with self.assertRaises(MemoryError): |
| 414 |
self.loop.run_until_complete(coro) |
| 415 |
self.assertTrue(sock.close.called) |
| 416 |
|
| 417 |
def test_create_unix_connection_path_sock(self): |
| 418 |
coro = self.loop.create_unix_connection( |
| 419 |
lambda: None, os.devnull, sock=object()) |
| 420 |
with self.assertRaisesRegex(ValueError, 'path and sock can not be'): |
| 421 |
self.loop.run_until_complete(coro) |
| 422 |
|
| 423 |
def test_create_unix_connection_nopath_nosock(self): |
| 424 |
coro = self.loop.create_unix_connection( |
| 425 |
lambda: None, None) |
| 426 |
with self.assertRaisesRegex(ValueError, |
| 427 |
'no path and sock were specified'): |
| 428 |
self.loop.run_until_complete(coro) |
| 429 |
|
| 430 |
def test_create_unix_connection_nossl_serverhost(self): |
| 431 |
coro = self.loop.create_unix_connection( |
| 432 |
lambda: None, os.devnull, server_hostname='spam') |
| 433 |
with self.assertRaisesRegex(ValueError, |
| 434 |
'server_hostname is only meaningful'): |
| 435 |
self.loop.run_until_complete(coro) |
| 436 |
|
| 437 |
def test_create_unix_connection_ssl_noserverhost(self): |
| 438 |
coro = self.loop.create_unix_connection( |
| 439 |
lambda: None, os.devnull, ssl=True) |
| 440 |
|
| 441 |
with self.assertRaisesRegex( |
| 442 |
ValueError, 'you have to pass server_hostname when using ssl'): |
| 443 |
|
| 444 |
self.loop.run_until_complete(coro) |
| 445 |
|
| 446 |
def test_create_unix_connection_ssl_timeout_with_plain_sock(self): |
| 447 |
coro = self.loop.create_unix_connection(lambda: None, path='spam', |
| 448 |
ssl_handshake_timeout=1) |
| 449 |
with self.assertRaisesRegex( |
| 450 |
ValueError, |
| 451 |
'ssl_handshake_timeout is only meaningful with ssl'): |
| 452 |
self.loop.run_until_complete(coro) |
| 453 |
|
| 454 |
|
| 455 |
@unittest.skipUnless(hasattr(os, 'sendfile'), |
| 456 |
'sendfile is not supported') |
| 457 |
class SelectorEventLoopUnixSockSendfileTests(test_utils.TestCase): |
| 458 |
DATA = b"12345abcde" * 16 * 1024 # 160 KiB |
| 459 |
|
| 460 |
class MyProto(asyncio.Protocol): |
| 461 |
|
| 462 |
def __init__(self, loop): |
| 463 |
self.started = False |
| 464 |
self.closed = False |
| 465 |
self.data = bytearray() |
| 466 |
self.fut = loop.create_future() |
| 467 |
self.transport = None |
| 468 |
self._ready = loop.create_future() |
| 469 |
|
| 470 |
def connection_made(self, transport): |
| 471 |
self.started = True |
| 472 |
self.transport = transport |
| 473 |
self._ready.set_result(None) |
| 474 |
|
| 475 |
def data_received(self, data): |
| 476 |
self.data.extend(data) |
| 477 |
|
| 478 |
def connection_lost(self, exc): |
| 479 |
self.closed = True |
| 480 |
self.fut.set_result(None) |
| 481 |
|
| 482 |
async def wait_closed(self): |
| 483 |
await self.fut |
| 484 |
|
| 485 |
@classmethod |
| 486 |
def setUpClass(cls): |
| 487 |
with open(os_helper.TESTFN, 'wb') as fp: |
| 488 |
fp.write(cls.DATA) |
| 489 |
super().setUpClass() |
| 490 |
|
| 491 |
@classmethod |
| 492 |
def tearDownClass(cls): |
| 493 |
os_helper.unlink(os_helper.TESTFN) |
| 494 |
super().tearDownClass() |
| 495 |
|
| 496 |
def setUp(self): |
| 497 |
self.loop = asyncio.new_event_loop() |
| 498 |
self.set_event_loop(self.loop) |
| 499 |
self.file = open(os_helper.TESTFN, 'rb') |
| 500 |
self.addCleanup(self.file.close) |
| 501 |
super().setUp() |
| 502 |
|
| 503 |
def make_socket(self, cleanup=True): |
| 504 |
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 505 |
sock.setblocking(False) |
| 506 |
sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 1024) |
| 507 |
sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 1024) |
| 508 |
if cleanup: |
| 509 |
self.addCleanup(sock.close) |
| 510 |
return sock |
| 511 |
|
| 512 |
def run_loop(self, coro): |
| 513 |
return self.loop.run_until_complete(coro) |
| 514 |
|
| 515 |
def prepare(self): |
| 516 |
sock = self.make_socket() |
| 517 |
proto = self.MyProto(self.loop) |
| 518 |
port = socket_helper.find_unused_port() |
| 519 |
srv_sock = self.make_socket(cleanup=False) |
| 520 |
srv_sock.bind((socket_helper.HOST, port)) |
| 521 |
server = self.run_loop(self.loop.create_server( |
| 522 |
lambda: proto, sock=srv_sock)) |
| 523 |
self.run_loop(self.loop.sock_connect(sock, (socket_helper.HOST, port))) |
| 524 |
self.run_loop(proto._ready) |
| 525 |
|
| 526 |
def cleanup(): |
| 527 |
proto.transport.close() |
| 528 |
self.run_loop(proto.wait_closed()) |
| 529 |
|
| 530 |
server.close() |
| 531 |
self.run_loop(server.wait_closed()) |
| 532 |
|
| 533 |
self.addCleanup(cleanup) |
| 534 |
|
| 535 |
return sock, proto |
| 536 |
|
| 537 |
def test_sock_sendfile_not_available(self): |
| 538 |
sock, proto = self.prepare() |
| 539 |
with mock.patch('asyncio.unix_events.os', spec=[]): |
| 540 |
with self.assertRaisesRegex(asyncio.SendfileNotAvailableError, |
| 541 |
"os[.]sendfile[(][)] is not available"): |
| 542 |
self.run_loop(self.loop._sock_sendfile_native(sock, self.file, |
| 543 |
0, None)) |
| 544 |
self.assertEqual(self.file.tell(), 0) |
| 545 |
|
| 546 |
def test_sock_sendfile_not_a_file(self): |
| 547 |
sock, proto = self.prepare() |
| 548 |
f = object() |
| 549 |
with self.assertRaisesRegex(asyncio.SendfileNotAvailableError, |
| 550 |
"not a regular file"): |
| 551 |
self.run_loop(self.loop._sock_sendfile_native(sock, f, |
| 552 |
0, None)) |
| 553 |
self.assertEqual(self.file.tell(), 0) |
| 554 |
|
| 555 |
def test_sock_sendfile_iobuffer(self): |
| 556 |
sock, proto = self.prepare() |
| 557 |
f = io.BytesIO() |
| 558 |
with self.assertRaisesRegex(asyncio.SendfileNotAvailableError, |
| 559 |
"not a regular file"): |
| 560 |
self.run_loop(self.loop._sock_sendfile_native(sock, f, |
| 561 |
0, None)) |
| 562 |
self.assertEqual(self.file.tell(), 0) |
| 563 |
|
| 564 |
def test_sock_sendfile_not_regular_file(self): |
| 565 |
sock, proto = self.prepare() |
| 566 |
f = mock.Mock() |
| 567 |
f.fileno.return_value = -1 |
| 568 |
with self.assertRaisesRegex(asyncio.SendfileNotAvailableError, |
| 569 |
"not a regular file"): |
| 570 |
self.run_loop(self.loop._sock_sendfile_native(sock, f, |
| 571 |
0, None)) |
| 572 |
self.assertEqual(self.file.tell(), 0) |
| 573 |
|
| 574 |
def test_sock_sendfile_cancel1(self): |
| 575 |
sock, proto = self.prepare() |
| 576 |
|
| 577 |
fut = self.loop.create_future() |
| 578 |
fileno = self.file.fileno() |
| 579 |
self.loop._sock_sendfile_native_impl(fut, None, sock, fileno, |
| 580 |
0, None, len(self.DATA), 0) |
| 581 |
fut.cancel() |
| 582 |
with contextlib.suppress(asyncio.CancelledError): |
| 583 |
self.run_loop(fut) |
| 584 |
with self.assertRaises(KeyError): |
| 585 |
self.loop._selector.get_key(sock) |
| 586 |
|
| 587 |
def test_sock_sendfile_cancel2(self): |
| 588 |
sock, proto = self.prepare() |
| 589 |
|
| 590 |
fut = self.loop.create_future() |
| 591 |
fileno = self.file.fileno() |
| 592 |
self.loop._sock_sendfile_native_impl(fut, None, sock, fileno, |
| 593 |
0, None, len(self.DATA), 0) |
| 594 |
fut.cancel() |
| 595 |
self.loop._sock_sendfile_native_impl(fut, sock.fileno(), sock, fileno, |
| 596 |
0, None, len(self.DATA), 0) |
| 597 |
with self.assertRaises(KeyError): |
| 598 |
self.loop._selector.get_key(sock) |
| 599 |
|
| 600 |
def test_sock_sendfile_blocking_error(self): |
| 601 |
sock, proto = self.prepare() |
| 602 |
|
| 603 |
fileno = self.file.fileno() |
| 604 |
fut = mock.Mock() |
| 605 |
fut.cancelled.return_value = False |
| 606 |
with mock.patch('os.sendfile', side_effect=BlockingIOError()): |
| 607 |
self.loop._sock_sendfile_native_impl(fut, None, sock, fileno, |
| 608 |
0, None, len(self.DATA), 0) |
| 609 |
key = self.loop._selector.get_key(sock) |
| 610 |
self.assertIsNotNone(key) |
| 611 |
fut.add_done_callback.assert_called_once_with(mock.ANY) |
| 612 |
|
| 613 |
def test_sock_sendfile_os_error_first_call(self): |
| 614 |
sock, proto = self.prepare() |
| 615 |
|
| 616 |
fileno = self.file.fileno() |
| 617 |
fut = self.loop.create_future() |
| 618 |
with mock.patch('os.sendfile', side_effect=OSError()): |
| 619 |
self.loop._sock_sendfile_native_impl(fut, None, sock, fileno, |
| 620 |
0, None, len(self.DATA), 0) |
| 621 |
with self.assertRaises(KeyError): |
| 622 |
self.loop._selector.get_key(sock) |
| 623 |
exc = fut.exception() |
| 624 |
self.assertIsInstance(exc, asyncio.SendfileNotAvailableError) |
| 625 |
self.assertEqual(0, self.file.tell()) |
| 626 |
|
| 627 |
def test_sock_sendfile_os_error_next_call(self): |
| 628 |
sock, proto = self.prepare() |
| 629 |
|
| 630 |
fileno = self.file.fileno() |
| 631 |
fut = self.loop.create_future() |
| 632 |
err = OSError() |
| 633 |
with mock.patch('os.sendfile', side_effect=err): |
| 634 |
self.loop._sock_sendfile_native_impl(fut, sock.fileno(), |
| 635 |
sock, fileno, |
| 636 |
1000, None, len(self.DATA), |
| 637 |
1000) |
| 638 |
with self.assertRaises(KeyError): |
| 639 |
self.loop._selector.get_key(sock) |
| 640 |
exc = fut.exception() |
| 641 |
self.assertIs(exc, err) |
| 642 |
self.assertEqual(1000, self.file.tell()) |
| 643 |
|
| 644 |
def test_sock_sendfile_exception(self): |
| 645 |
sock, proto = self.prepare() |
| 646 |
|
| 647 |
fileno = self.file.fileno() |
| 648 |
fut = self.loop.create_future() |
| 649 |
err = asyncio.SendfileNotAvailableError() |
| 650 |
with mock.patch('os.sendfile', side_effect=err): |
| 651 |
self.loop._sock_sendfile_native_impl(fut, sock.fileno(), |
| 652 |
sock, fileno, |
| 653 |
1000, None, len(self.DATA), |
| 654 |
1000) |
| 655 |
with self.assertRaises(KeyError): |
| 656 |
self.loop._selector.get_key(sock) |
| 657 |
exc = fut.exception() |
| 658 |
self.assertIs(exc, err) |
| 659 |
self.assertEqual(1000, self.file.tell()) |
| 660 |
|
| 661 |
|
| 662 |
class UnixReadPipeTransportTests(test_utils.TestCase): |
| 663 |
|
| 664 |
def setUp(self): |
| 665 |
super().setUp() |
| 666 |
self.loop = self.new_test_loop() |
| 667 |
self.protocol = test_utils.make_test_protocol(asyncio.Protocol) |
| 668 |
self.pipe = mock.Mock(spec_set=io.RawIOBase) |
| 669 |
self.pipe.fileno.return_value = 5 |
| 670 |
|
| 671 |
blocking_patcher = mock.patch('os.set_blocking') |
| 672 |
blocking_patcher.start() |
| 673 |
self.addCleanup(blocking_patcher.stop) |
| 674 |
|
| 675 |
fstat_patcher = mock.patch('os.fstat') |
| 676 |
m_fstat = fstat_patcher.start() |
| 677 |
st = mock.Mock() |
| 678 |
st.st_mode = stat.S_IFIFO |
| 679 |
m_fstat.return_value = st |
| 680 |
self.addCleanup(fstat_patcher.stop) |
| 681 |
|
| 682 |
def read_pipe_transport(self, waiter=None): |
| 683 |
transport = unix_events._UnixReadPipeTransport(self.loop, self.pipe, |
| 684 |
self.protocol, |
| 685 |
waiter=waiter) |
| 686 |
self.addCleanup(close_pipe_transport, transport) |
| 687 |
return transport |
| 688 |
|
| 689 |
def test_ctor(self): |
| 690 |
waiter = self.loop.create_future() |
| 691 |
tr = self.read_pipe_transport(waiter=waiter) |
| 692 |
self.loop.run_until_complete(waiter) |
| 693 |
|
| 694 |
self.protocol.connection_made.assert_called_with(tr) |
| 695 |
self.loop.assert_reader(5, tr._read_ready) |
| 696 |
self.assertIsNone(waiter.result()) |
| 697 |
|
| 698 |
@mock.patch('os.read') |
| 699 |
def test__read_ready(self, m_read): |
| 700 |
tr = self.read_pipe_transport() |
| 701 |
m_read.return_value = b'data' |
| 702 |
tr._read_ready() |
| 703 |
|
| 704 |
m_read.assert_called_with(5, tr.max_size) |
| 705 |
self.protocol.data_received.assert_called_with(b'data') |
| 706 |
|
| 707 |
@mock.patch('os.read') |
| 708 |
def test__read_ready_eof(self, m_read): |
| 709 |
tr = self.read_pipe_transport() |
| 710 |
m_read.return_value = b'' |
| 711 |
tr._read_ready() |
| 712 |
|
| 713 |
m_read.assert_called_with(5, tr.max_size) |
| 714 |
self.assertFalse(self.loop.readers) |
| 715 |
test_utils.run_briefly(self.loop) |
| 716 |
self.protocol.eof_received.assert_called_with() |
| 717 |
self.protocol.connection_lost.assert_called_with(None) |
| 718 |
|
| 719 |
@mock.patch('os.read') |
| 720 |
def test__read_ready_blocked(self, m_read): |
| 721 |
tr = self.read_pipe_transport() |
| 722 |
m_read.side_effect = BlockingIOError |
| 723 |
tr._read_ready() |
| 724 |
|
| 725 |
m_read.assert_called_with(5, tr.max_size) |
| 726 |
test_utils.run_briefly(self.loop) |
| 727 |
self.assertFalse(self.protocol.data_received.called) |
| 728 |
|
| 729 |
@mock.patch('asyncio.log.logger.error') |
| 730 |
@mock.patch('os.read') |
| 731 |
def test__read_ready_error(self, m_read, m_logexc): |
| 732 |
tr = self.read_pipe_transport() |
| 733 |
err = OSError() |
| 734 |
m_read.side_effect = err |
| 735 |
tr._close = mock.Mock() |
| 736 |
tr._read_ready() |
| 737 |
|
| 738 |
m_read.assert_called_with(5, tr.max_size) |
| 739 |
tr._close.assert_called_with(err) |
| 740 |
m_logexc.assert_called_with( |
| 741 |
test_utils.MockPattern( |
| 742 |
'Fatal read error on pipe transport' |
| 743 |
'\nprotocol:.*\ntransport:.*'), |
| 744 |
exc_info=(OSError, MOCK_ANY, MOCK_ANY)) |
| 745 |
|
| 746 |
@mock.patch('os.read') |
| 747 |
def test_pause_reading(self, m_read): |
| 748 |
tr = self.read_pipe_transport() |
| 749 |
m = mock.Mock() |
| 750 |
self.loop.add_reader(5, m) |
| 751 |
tr.pause_reading() |
| 752 |
self.assertFalse(self.loop.readers) |
| 753 |
|
| 754 |
@mock.patch('os.read') |
| 755 |
def test_resume_reading(self, m_read): |
| 756 |
tr = self.read_pipe_transport() |
| 757 |
tr.pause_reading() |
| 758 |
tr.resume_reading() |
| 759 |
self.loop.assert_reader(5, tr._read_ready) |
| 760 |
|
| 761 |
@mock.patch('os.read') |
| 762 |
def test_close(self, m_read): |
| 763 |
tr = self.read_pipe_transport() |
| 764 |
tr._close = mock.Mock() |
| 765 |
tr.close() |
| 766 |
tr._close.assert_called_with(None) |
| 767 |
|
| 768 |
@mock.patch('os.read') |
| 769 |
def test_close_already_closing(self, m_read): |
| 770 |
tr = self.read_pipe_transport() |
| 771 |
tr._closing = True |
| 772 |
tr._close = mock.Mock() |
| 773 |
tr.close() |
| 774 |
self.assertFalse(tr._close.called) |
| 775 |
|
| 776 |
@mock.patch('os.read') |
| 777 |
def test__close(self, m_read): |
| 778 |
tr = self.read_pipe_transport() |
| 779 |
err = object() |
| 780 |
tr._close(err) |
| 781 |
self.assertTrue(tr.is_closing()) |
| 782 |
self.assertFalse(self.loop.readers) |
| 783 |
test_utils.run_briefly(self.loop) |
| 784 |
self.protocol.connection_lost.assert_called_with(err) |
| 785 |
|
| 786 |
def test__call_connection_lost(self): |
| 787 |
tr = self.read_pipe_transport() |
| 788 |
self.assertIsNotNone(tr._protocol) |
| 789 |
self.assertIsNotNone(tr._loop) |
| 790 |
|
| 791 |
err = None |
| 792 |
tr._call_connection_lost(err) |
| 793 |
self.protocol.connection_lost.assert_called_with(err) |
| 794 |
self.pipe.close.assert_called_with() |
| 795 |
|
| 796 |
self.assertIsNone(tr._protocol) |
| 797 |
self.assertIsNone(tr._loop) |
| 798 |
|
| 799 |
def test__call_connection_lost_with_err(self): |
| 800 |
tr = self.read_pipe_transport() |
| 801 |
self.assertIsNotNone(tr._protocol) |
| 802 |
self.assertIsNotNone(tr._loop) |
| 803 |
|
| 804 |
err = OSError() |
| 805 |
tr._call_connection_lost(err) |
| 806 |
self.protocol.connection_lost.assert_called_with(err) |
| 807 |
self.pipe.close.assert_called_with() |
| 808 |
|
| 809 |
self.assertIsNone(tr._protocol) |
| 810 |
self.assertIsNone(tr._loop) |
| 811 |
|
| 812 |
def test_pause_reading_on_closed_pipe(self): |
| 813 |
tr = self.read_pipe_transport() |
| 814 |
tr.close() |
| 815 |
test_utils.run_briefly(self.loop) |
| 816 |
self.assertIsNone(tr._loop) |
| 817 |
tr.pause_reading() |
| 818 |
|
| 819 |
def test_pause_reading_on_paused_pipe(self): |
| 820 |
tr = self.read_pipe_transport() |
| 821 |
tr.pause_reading() |
| 822 |
# the second call should do nothing |
| 823 |
tr.pause_reading() |
| 824 |
|
| 825 |
def test_resume_reading_on_closed_pipe(self): |
| 826 |
tr = self.read_pipe_transport() |
| 827 |
tr.close() |
| 828 |
test_utils.run_briefly(self.loop) |
| 829 |
self.assertIsNone(tr._loop) |
| 830 |
tr.resume_reading() |
| 831 |
|
| 832 |
def test_resume_reading_on_paused_pipe(self): |
| 833 |
tr = self.read_pipe_transport() |
| 834 |
# the pipe is not paused |
| 835 |
# resuming should do nothing |
| 836 |
tr.resume_reading() |
| 837 |
|
| 838 |
|
| 839 |
class UnixWritePipeTransportTests(test_utils.TestCase): |
| 840 |
|
| 841 |
def setUp(self): |
| 842 |
super().setUp() |
| 843 |
self.loop = self.new_test_loop() |
| 844 |
self.protocol = test_utils.make_test_protocol(asyncio.BaseProtocol) |
| 845 |
self.pipe = mock.Mock(spec_set=io.RawIOBase) |
| 846 |
self.pipe.fileno.return_value = 5 |
| 847 |
|
| 848 |
blocking_patcher = mock.patch('os.set_blocking') |
| 849 |
blocking_patcher.start() |
| 850 |
self.addCleanup(blocking_patcher.stop) |
| 851 |
|
| 852 |
fstat_patcher = mock.patch('os.fstat') |
| 853 |
m_fstat = fstat_patcher.start() |
| 854 |
st = mock.Mock() |
| 855 |
st.st_mode = stat.S_IFSOCK |
| 856 |
m_fstat.return_value = st |
| 857 |
self.addCleanup(fstat_patcher.stop) |
| 858 |
|
| 859 |
def write_pipe_transport(self, waiter=None): |
| 860 |
transport = unix_events._UnixWritePipeTransport(self.loop, self.pipe, |
| 861 |
self.protocol, |
| 862 |
waiter=waiter) |
| 863 |
self.addCleanup(close_pipe_transport, transport) |
| 864 |
return transport |
| 865 |
|
| 866 |
def test_ctor(self): |
| 867 |
waiter = self.loop.create_future() |
| 868 |
tr = self.write_pipe_transport(waiter=waiter) |
| 869 |
self.loop.run_until_complete(waiter) |
| 870 |
|
| 871 |
self.protocol.connection_made.assert_called_with(tr) |
| 872 |
self.loop.assert_reader(5, tr._read_ready) |
| 873 |
self.assertEqual(None, waiter.result()) |
| 874 |
|
| 875 |
def test_can_write_eof(self): |
| 876 |
tr = self.write_pipe_transport() |
| 877 |
self.assertTrue(tr.can_write_eof()) |
| 878 |
|
| 879 |
@mock.patch('os.write') |
| 880 |
def test_write(self, m_write): |
| 881 |
tr = self.write_pipe_transport() |
| 882 |
m_write.return_value = 4 |
| 883 |
tr.write(b'data') |
| 884 |
m_write.assert_called_with(5, b'data') |
| 885 |
self.assertFalse(self.loop.writers) |
| 886 |
self.assertEqual(bytearray(), tr._buffer) |
| 887 |
|
| 888 |
@mock.patch('os.write') |
| 889 |
def test_write_no_data(self, m_write): |
| 890 |
tr = self.write_pipe_transport() |
| 891 |
tr.write(b'') |
| 892 |
self.assertFalse(m_write.called) |
| 893 |
self.assertFalse(self.loop.writers) |
| 894 |
self.assertEqual(bytearray(b''), tr._buffer) |
| 895 |
|
| 896 |
@mock.patch('os.write') |
| 897 |
def test_write_partial(self, m_write): |
| 898 |
tr = self.write_pipe_transport() |
| 899 |
m_write.return_value = 2 |
| 900 |
tr.write(b'data') |
| 901 |
self.loop.assert_writer(5, tr._write_ready) |
| 902 |
self.assertEqual(bytearray(b'ta'), tr._buffer) |
| 903 |
|
| 904 |
@mock.patch('os.write') |
| 905 |
def test_write_buffer(self, m_write): |
| 906 |
tr = self.write_pipe_transport() |
| 907 |
self.loop.add_writer(5, tr._write_ready) |
| 908 |
tr._buffer = bytearray(b'previous') |
| 909 |
tr.write(b'data') |
| 910 |
self.assertFalse(m_write.called) |
| 911 |
self.loop.assert_writer(5, tr._write_ready) |
| 912 |
self.assertEqual(bytearray(b'previousdata'), tr._buffer) |
| 913 |
|
| 914 |
@mock.patch('os.write') |
| 915 |
def test_write_again(self, m_write): |
| 916 |
tr = self.write_pipe_transport() |
| 917 |
m_write.side_effect = BlockingIOError() |
| 918 |
tr.write(b'data') |
| 919 |
m_write.assert_called_with(5, bytearray(b'data')) |
| 920 |
self.loop.assert_writer(5, tr._write_ready) |
| 921 |
self.assertEqual(bytearray(b'data'), tr._buffer) |
| 922 |
|
| 923 |
@mock.patch('asyncio.unix_events.logger') |
| 924 |
@mock.patch('os.write') |
| 925 |
def test_write_err(self, m_write, m_log): |
| 926 |
tr = self.write_pipe_transport() |
| 927 |
err = OSError() |
| 928 |
m_write.side_effect = err |
| 929 |
tr._fatal_error = mock.Mock() |
| 930 |
tr.write(b'data') |
| 931 |
m_write.assert_called_with(5, b'data') |
| 932 |
self.assertFalse(self.loop.writers) |
| 933 |
self.assertEqual(bytearray(), tr._buffer) |
| 934 |
tr._fatal_error.assert_called_with( |
| 935 |
err, |
| 936 |
'Fatal write error on pipe transport') |
| 937 |
self.assertEqual(1, tr._conn_lost) |
| 938 |
|
| 939 |
tr.write(b'data') |
| 940 |
self.assertEqual(2, tr._conn_lost) |
| 941 |
tr.write(b'data') |
| 942 |
tr.write(b'data') |
| 943 |
tr.write(b'data') |
| 944 |
tr.write(b'data') |
| 945 |
# This is a bit overspecified. :-( |
| 946 |
m_log.warning.assert_called_with( |
| 947 |
'pipe closed by peer or os.write(pipe, data) raised exception.') |
| 948 |
tr.close() |
| 949 |
|
| 950 |
@mock.patch('os.write') |
| 951 |
def test_write_close(self, m_write): |
| 952 |
tr = self.write_pipe_transport() |
| 953 |
tr._read_ready() # pipe was closed by peer |
| 954 |
|
| 955 |
tr.write(b'data') |
| 956 |
self.assertEqual(tr._conn_lost, 1) |
| 957 |
tr.write(b'data') |
| 958 |
self.assertEqual(tr._conn_lost, 2) |
| 959 |
|
| 960 |
def test__read_ready(self): |
| 961 |
tr = self.write_pipe_transport() |
| 962 |
tr._read_ready() |
| 963 |
self.assertFalse(self.loop.readers) |
| 964 |
self.assertFalse(self.loop.writers) |
| 965 |
self.assertTrue(tr.is_closing()) |
| 966 |
test_utils.run_briefly(self.loop) |
| 967 |
self.protocol.connection_lost.assert_called_with(None) |
| 968 |
|
| 969 |
@mock.patch('os.write') |
| 970 |
def test__write_ready(self, m_write): |
| 971 |
tr = self.write_pipe_transport() |
| 972 |
self.loop.add_writer(5, tr._write_ready) |
| 973 |
tr._buffer = bytearray(b'data') |
| 974 |
m_write.return_value = 4 |
| 975 |
tr._write_ready() |
| 976 |
self.assertFalse(self.loop.writers) |
| 977 |
self.assertEqual(bytearray(), tr._buffer) |
| 978 |
|
| 979 |
@mock.patch('os.write') |
| 980 |
def test__write_ready_partial(self, m_write): |
| 981 |
tr = self.write_pipe_transport() |
| 982 |
self.loop.add_writer(5, tr._write_ready) |
| 983 |
tr._buffer = bytearray(b'data') |
| 984 |
m_write.return_value = 3 |
| 985 |
tr._write_ready() |
| 986 |
self.loop.assert_writer(5, tr._write_ready) |
| 987 |
self.assertEqual(bytearray(b'a'), tr._buffer) |
| 988 |
|
| 989 |
@mock.patch('os.write') |
| 990 |
def test__write_ready_again(self, m_write): |
| 991 |
tr = self.write_pipe_transport() |
| 992 |
self.loop.add_writer(5, tr._write_ready) |
| 993 |
tr._buffer = bytearray(b'data') |
| 994 |
m_write.side_effect = BlockingIOError() |
| 995 |
tr._write_ready() |
| 996 |
m_write.assert_called_with(5, bytearray(b'data')) |
| 997 |
self.loop.assert_writer(5, tr._write_ready) |
| 998 |
self.assertEqual(bytearray(b'data'), tr._buffer) |
| 999 |
|
| 1000 |
@mock.patch('os.write') |
| 1001 |
def test__write_ready_empty(self, m_write): |
| 1002 |
tr = self.write_pipe_transport() |
| 1003 |
self.loop.add_writer(5, tr._write_ready) |
| 1004 |
tr._buffer = bytearray(b'data') |
| 1005 |
m_write.return_value = 0 |
| 1006 |
tr._write_ready() |
| 1007 |
m_write.assert_called_with(5, bytearray(b'data')) |
| 1008 |
self.loop.assert_writer(5, tr._write_ready) |
| 1009 |
self.assertEqual(bytearray(b'data'), tr._buffer) |
| 1010 |
|
| 1011 |
@mock.patch('asyncio.log.logger.error') |
| 1012 |
@mock.patch('os.write') |
| 1013 |
def test__write_ready_err(self, m_write, m_logexc): |
| 1014 |
tr = self.write_pipe_transport() |
| 1015 |
self.loop.add_writer(5, tr._write_ready) |
| 1016 |
tr._buffer = bytearray(b'data') |
| 1017 |
m_write.side_effect = err = OSError() |
| 1018 |
tr._write_ready() |
| 1019 |
self.assertFalse(self.loop.writers) |
| 1020 |
self.assertFalse(self.loop.readers) |
| 1021 |
self.assertEqual(bytearray(), tr._buffer) |
| 1022 |
self.assertTrue(tr.is_closing()) |
| 1023 |
m_logexc.assert_not_called() |
| 1024 |
self.assertEqual(1, tr._conn_lost) |
| 1025 |
test_utils.run_briefly(self.loop) |
| 1026 |
self.protocol.connection_lost.assert_called_with(err) |
| 1027 |
|
| 1028 |
@mock.patch('os.write') |
| 1029 |
def test__write_ready_closing(self, m_write): |
| 1030 |
tr = self.write_pipe_transport() |
| 1031 |
self.loop.add_writer(5, tr._write_ready) |
| 1032 |
tr._closing = True |
| 1033 |
tr._buffer = bytearray(b'data') |
| 1034 |
m_write.return_value = 4 |
| 1035 |
tr._write_ready() |
| 1036 |
self.assertFalse(self.loop.writers) |
| 1037 |
self.assertFalse(self.loop.readers) |
| 1038 |
self.assertEqual(bytearray(), tr._buffer) |
| 1039 |
self.protocol.connection_lost.assert_called_with(None) |
| 1040 |
self.pipe.close.assert_called_with() |
| 1041 |
|
| 1042 |
@mock.patch('os.write') |
| 1043 |
def test_abort(self, m_write): |
| 1044 |
tr = self.write_pipe_transport() |
| 1045 |
self.loop.add_writer(5, tr._write_ready) |
| 1046 |
self.loop.add_reader(5, tr._read_ready) |
| 1047 |
tr._buffer = [b'da', b'ta'] |
| 1048 |
tr.abort() |
| 1049 |
self.assertFalse(m_write.called) |
| 1050 |
self.assertFalse(self.loop.readers) |
| 1051 |
self.assertFalse(self.loop.writers) |
| 1052 |
self.assertEqual([], tr._buffer) |
| 1053 |
self.assertTrue(tr.is_closing()) |
| 1054 |
test_utils.run_briefly(self.loop) |
| 1055 |
self.protocol.connection_lost.assert_called_with(None) |
| 1056 |
|
| 1057 |
def test__call_connection_lost(self): |
| 1058 |
tr = self.write_pipe_transport() |
| 1059 |
self.assertIsNotNone(tr._protocol) |
| 1060 |
self.assertIsNotNone(tr._loop) |
| 1061 |
|
| 1062 |
err = None |
| 1063 |
tr._call_connection_lost(err) |
| 1064 |
self.protocol.connection_lost.assert_called_with(err) |
| 1065 |
self.pipe.close.assert_called_with() |
| 1066 |
|
| 1067 |
self.assertIsNone(tr._protocol) |
| 1068 |
self.assertIsNone(tr._loop) |
| 1069 |
|
| 1070 |
def test__call_connection_lost_with_err(self): |
| 1071 |
tr = self.write_pipe_transport() |
| 1072 |
self.assertIsNotNone(tr._protocol) |
| 1073 |
self.assertIsNotNone(tr._loop) |
| 1074 |
|
| 1075 |
err = OSError() |
| 1076 |
tr._call_connection_lost(err) |
| 1077 |
self.protocol.connection_lost.assert_called_with(err) |
| 1078 |
self.pipe.close.assert_called_with() |
| 1079 |
|
| 1080 |
self.assertIsNone(tr._protocol) |
| 1081 |
self.assertIsNone(tr._loop) |
| 1082 |
|
| 1083 |
def test_close(self): |
| 1084 |
tr = self.write_pipe_transport() |
| 1085 |
tr.write_eof = mock.Mock() |
| 1086 |
tr.close() |
| 1087 |
tr.write_eof.assert_called_with() |
| 1088 |
|
| 1089 |
# closing the transport twice must not fail |
| 1090 |
tr.close() |
| 1091 |
|
| 1092 |
def test_close_closing(self): |
| 1093 |
tr = self.write_pipe_transport() |
| 1094 |
tr.write_eof = mock.Mock() |
| 1095 |
tr._closing = True |
| 1096 |
tr.close() |
| 1097 |
self.assertFalse(tr.write_eof.called) |
| 1098 |
|
| 1099 |
def test_write_eof(self): |
| 1100 |
tr = self.write_pipe_transport() |
| 1101 |
tr.write_eof() |
| 1102 |
self.assertTrue(tr.is_closing()) |
| 1103 |
self.assertFalse(self.loop.readers) |
| 1104 |
test_utils.run_briefly(self.loop) |
| 1105 |
self.protocol.connection_lost.assert_called_with(None) |
| 1106 |
|
| 1107 |
def test_write_eof_pending(self): |
| 1108 |
tr = self.write_pipe_transport() |
| 1109 |
tr._buffer = [b'data'] |
| 1110 |
tr.write_eof() |
| 1111 |
self.assertTrue(tr.is_closing()) |
| 1112 |
self.assertFalse(self.protocol.connection_lost.called) |
| 1113 |
|
| 1114 |
|
| 1115 |
class AbstractChildWatcherTests(unittest.TestCase): |
| 1116 |
|
| 1117 |
def test_warns_on_subclassing(self): |
| 1118 |
with self.assertWarns(DeprecationWarning): |
| 1119 |
class MyWatcher(asyncio.AbstractChildWatcher): |
| 1120 |
pass |
| 1121 |
|
| 1122 |
def test_not_implemented(self): |
| 1123 |
f = mock.Mock() |
| 1124 |
watcher = asyncio.AbstractChildWatcher() |
| 1125 |
self.assertRaises( |
| 1126 |
NotImplementedError, watcher.add_child_handler, f, f) |
| 1127 |
self.assertRaises( |
| 1128 |
NotImplementedError, watcher.remove_child_handler, f) |
| 1129 |
self.assertRaises( |
| 1130 |
NotImplementedError, watcher.attach_loop, f) |
| 1131 |
self.assertRaises( |
| 1132 |
NotImplementedError, watcher.close) |
| 1133 |
self.assertRaises( |
| 1134 |
NotImplementedError, watcher.is_active) |
| 1135 |
self.assertRaises( |
| 1136 |
NotImplementedError, watcher.__enter__) |
| 1137 |
self.assertRaises( |
| 1138 |
NotImplementedError, watcher.__exit__, f, f, f) |
| 1139 |
|
| 1140 |
|
| 1141 |
class BaseChildWatcherTests(unittest.TestCase): |
| 1142 |
|
| 1143 |
def test_not_implemented(self): |
| 1144 |
f = mock.Mock() |
| 1145 |
watcher = unix_events.BaseChildWatcher() |
| 1146 |
self.assertRaises( |
| 1147 |
NotImplementedError, watcher._do_waitpid, f) |
| 1148 |
|
| 1149 |
|
| 1150 |
class ChildWatcherTestsMixin: |
| 1151 |
|
| 1152 |
ignore_warnings = mock.patch.object(log.logger, "warning") |
| 1153 |
|
| 1154 |
def setUp(self): |
| 1155 |
super().setUp() |
| 1156 |
self.loop = self.new_test_loop() |
| 1157 |
self.running = False |
| 1158 |
self.zombies = {} |
| 1159 |
|
| 1160 |
with mock.patch.object( |
| 1161 |
self.loop, "add_signal_handler") as self.m_add_signal_handler: |
| 1162 |
self.watcher = self.create_watcher() |
| 1163 |
self.watcher.attach_loop(self.loop) |
| 1164 |
|
| 1165 |
def waitpid(self, pid, flags): |
| 1166 |
if isinstance(self.watcher, asyncio.SafeChildWatcher) or pid != -1: |
| 1167 |
self.assertGreater(pid, 0) |
| 1168 |
try: |
| 1169 |
if pid < 0: |
| 1170 |
return self.zombies.popitem() |
| 1171 |
else: |
| 1172 |
return pid, self.zombies.pop(pid) |
| 1173 |
except KeyError: |
| 1174 |
pass |
| 1175 |
if self.running: |
| 1176 |
return 0, 0 |
| 1177 |
else: |
| 1178 |
raise ChildProcessError() |
| 1179 |
|
| 1180 |
def add_zombie(self, pid, status): |
| 1181 |
self.zombies[pid] = status |
| 1182 |
|
| 1183 |
def waitstatus_to_exitcode(self, status): |
| 1184 |
if status > 32768: |
| 1185 |
return status - 32768 |
| 1186 |
elif 32700 < status < 32768: |
| 1187 |
return status - 32768 |
| 1188 |
else: |
| 1189 |
return status |
| 1190 |
|
| 1191 |
def test_create_watcher(self): |
| 1192 |
self.m_add_signal_handler.assert_called_once_with( |
| 1193 |
signal.SIGCHLD, self.watcher._sig_chld) |
| 1194 |
|
| 1195 |
def waitpid_mocks(func): |
| 1196 |
def wrapped_func(self): |
| 1197 |
def patch(target, wrapper): |
| 1198 |
return mock.patch(target, wraps=wrapper, |
| 1199 |
new_callable=mock.Mock) |
| 1200 |
|
| 1201 |
with patch('asyncio.unix_events.waitstatus_to_exitcode', self.waitstatus_to_exitcode), \ |
| 1202 |
patch('os.waitpid', self.waitpid) as m_waitpid: |
| 1203 |
func(self, m_waitpid) |
| 1204 |
return wrapped_func |
| 1205 |
|
| 1206 |
@waitpid_mocks |
| 1207 |
def test_sigchld(self, m_waitpid): |
| 1208 |
# register a child |
| 1209 |
callback = mock.Mock() |
| 1210 |
|
| 1211 |
with self.watcher: |
| 1212 |
self.running = True |
| 1213 |
self.watcher.add_child_handler(42, callback, 9, 10, 14) |
| 1214 |
|
| 1215 |
self.assertFalse(callback.called) |
| 1216 |
|
| 1217 |
# child is running |
| 1218 |
self.watcher._sig_chld() |
| 1219 |
|
| 1220 |
self.assertFalse(callback.called) |
| 1221 |
|
| 1222 |
# child terminates (returncode 12) |
| 1223 |
self.running = False |
| 1224 |
self.add_zombie(42, EXITCODE(12)) |
| 1225 |
self.watcher._sig_chld() |
| 1226 |
|
| 1227 |
callback.assert_called_once_with(42, 12, 9, 10, 14) |
| 1228 |
|
| 1229 |
callback.reset_mock() |
| 1230 |
|
| 1231 |
# ensure that the child is effectively reaped |
| 1232 |
self.add_zombie(42, EXITCODE(13)) |
| 1233 |
with self.ignore_warnings: |
| 1234 |
self.watcher._sig_chld() |
| 1235 |
|
| 1236 |
self.assertFalse(callback.called) |
| 1237 |
|
| 1238 |
# sigchld called again |
| 1239 |
self.zombies.clear() |
| 1240 |
self.watcher._sig_chld() |
| 1241 |
|
| 1242 |
self.assertFalse(callback.called) |
| 1243 |
|
| 1244 |
@waitpid_mocks |
| 1245 |
def test_sigchld_two_children(self, m_waitpid): |
| 1246 |
callback1 = mock.Mock() |
| 1247 |
callback2 = mock.Mock() |
| 1248 |
|
| 1249 |
# register child 1 |
| 1250 |
with self.watcher: |
| 1251 |
self.running = True |
| 1252 |
self.watcher.add_child_handler(43, callback1, 7, 8) |
| 1253 |
|
| 1254 |
self.assertFalse(callback1.called) |
| 1255 |
self.assertFalse(callback2.called) |
| 1256 |
|
| 1257 |
# register child 2 |
| 1258 |
with self.watcher: |
| 1259 |
self.watcher.add_child_handler(44, callback2, 147, 18) |
| 1260 |
|
| 1261 |
self.assertFalse(callback1.called) |
| 1262 |
self.assertFalse(callback2.called) |
| 1263 |
|
| 1264 |
# children are running |
| 1265 |
self.watcher._sig_chld() |
| 1266 |
|
| 1267 |
self.assertFalse(callback1.called) |
| 1268 |
self.assertFalse(callback2.called) |
| 1269 |
|
| 1270 |
# child 1 terminates (signal 3) |
| 1271 |
self.add_zombie(43, SIGNAL(3)) |
| 1272 |
self.watcher._sig_chld() |
| 1273 |
|
| 1274 |
callback1.assert_called_once_with(43, -3, 7, 8) |
| 1275 |
self.assertFalse(callback2.called) |
| 1276 |
|
| 1277 |
callback1.reset_mock() |
| 1278 |
|
| 1279 |
# child 2 still running |
| 1280 |
self.watcher._sig_chld() |
| 1281 |
|
| 1282 |
self.assertFalse(callback1.called) |
| 1283 |
self.assertFalse(callback2.called) |
| 1284 |
|
| 1285 |
# child 2 terminates (code 108) |
| 1286 |
self.add_zombie(44, EXITCODE(108)) |
| 1287 |
self.running = False |
| 1288 |
self.watcher._sig_chld() |
| 1289 |
|
| 1290 |
callback2.assert_called_once_with(44, 108, 147, 18) |
| 1291 |
self.assertFalse(callback1.called) |
| 1292 |
|
| 1293 |
callback2.reset_mock() |
| 1294 |
|
| 1295 |
# ensure that the children are effectively reaped |
| 1296 |
self.add_zombie(43, EXITCODE(14)) |
| 1297 |
self.add_zombie(44, EXITCODE(15)) |
| 1298 |
with self.ignore_warnings: |
| 1299 |
self.watcher._sig_chld() |
| 1300 |
|
| 1301 |
self.assertFalse(callback1.called) |
| 1302 |
self.assertFalse(callback2.called) |
| 1303 |
|
| 1304 |
# sigchld called again |
| 1305 |
self.zombies.clear() |
| 1306 |
self.watcher._sig_chld() |
| 1307 |
|
| 1308 |
self.assertFalse(callback1.called) |
| 1309 |
self.assertFalse(callback2.called) |
| 1310 |
|
| 1311 |
@waitpid_mocks |
| 1312 |
def test_sigchld_two_children_terminating_together(self, m_waitpid): |
| 1313 |
callback1 = mock.Mock() |
| 1314 |
callback2 = mock.Mock() |
| 1315 |
|
| 1316 |
# register child 1 |
| 1317 |
with self.watcher: |
| 1318 |
self.running = True |
| 1319 |
self.watcher.add_child_handler(45, callback1, 17, 8) |
| 1320 |
|
| 1321 |
self.assertFalse(callback1.called) |
| 1322 |
self.assertFalse(callback2.called) |
| 1323 |
|
| 1324 |
# register child 2 |
| 1325 |
with self.watcher: |
| 1326 |
self.watcher.add_child_handler(46, callback2, 1147, 18) |
| 1327 |
|
| 1328 |
self.assertFalse(callback1.called) |
| 1329 |
self.assertFalse(callback2.called) |
| 1330 |
|
| 1331 |
# children are running |
| 1332 |
self.watcher._sig_chld() |
| 1333 |
|
| 1334 |
self.assertFalse(callback1.called) |
| 1335 |
self.assertFalse(callback2.called) |
| 1336 |
|
| 1337 |
# child 1 terminates (code 78) |
| 1338 |
# child 2 terminates (signal 5) |
| 1339 |
self.add_zombie(45, EXITCODE(78)) |
| 1340 |
self.add_zombie(46, SIGNAL(5)) |
| 1341 |
self.running = False |
| 1342 |
self.watcher._sig_chld() |
| 1343 |
|
| 1344 |
callback1.assert_called_once_with(45, 78, 17, 8) |
| 1345 |
callback2.assert_called_once_with(46, -5, 1147, 18) |
| 1346 |
|
| 1347 |
callback1.reset_mock() |
| 1348 |
callback2.reset_mock() |
| 1349 |
|
| 1350 |
# ensure that the children are effectively reaped |
| 1351 |
self.add_zombie(45, EXITCODE(14)) |
| 1352 |
self.add_zombie(46, EXITCODE(15)) |
| 1353 |
with self.ignore_warnings: |
| 1354 |
self.watcher._sig_chld() |
| 1355 |
|
| 1356 |
self.assertFalse(callback1.called) |
| 1357 |
self.assertFalse(callback2.called) |
| 1358 |
|
| 1359 |
@waitpid_mocks |
| 1360 |
def test_sigchld_race_condition(self, m_waitpid): |
| 1361 |
# register a child |
| 1362 |
callback = mock.Mock() |
| 1363 |
|
| 1364 |
with self.watcher: |
| 1365 |
# child terminates before being registered |
| 1366 |
self.add_zombie(50, EXITCODE(4)) |
| 1367 |
self.watcher._sig_chld() |
| 1368 |
|
| 1369 |
self.watcher.add_child_handler(50, callback, 1, 12) |
| 1370 |
|
| 1371 |
callback.assert_called_once_with(50, 4, 1, 12) |
| 1372 |
callback.reset_mock() |
| 1373 |
|
| 1374 |
# ensure that the child is effectively reaped |
| 1375 |
self.add_zombie(50, SIGNAL(1)) |
| 1376 |
with self.ignore_warnings: |
| 1377 |
self.watcher._sig_chld() |
| 1378 |
|
| 1379 |
self.assertFalse(callback.called) |
| 1380 |
|
| 1381 |
@waitpid_mocks |
| 1382 |
def test_sigchld_replace_handler(self, m_waitpid): |
| 1383 |
callback1 = mock.Mock() |
| 1384 |
callback2 = mock.Mock() |
| 1385 |
|
| 1386 |
# register a child |
| 1387 |
with self.watcher: |
| 1388 |
self.running = True |
| 1389 |
self.watcher.add_child_handler(51, callback1, 19) |
| 1390 |
|
| 1391 |
self.assertFalse(callback1.called) |
| 1392 |
self.assertFalse(callback2.called) |
| 1393 |
|
| 1394 |
# register the same child again |
| 1395 |
with self.watcher: |
| 1396 |
self.watcher.add_child_handler(51, callback2, 21) |
| 1397 |
|
| 1398 |
self.assertFalse(callback1.called) |
| 1399 |
self.assertFalse(callback2.called) |
| 1400 |
|
| 1401 |
# child terminates (signal 8) |
| 1402 |
self.running = False |
| 1403 |
self.add_zombie(51, SIGNAL(8)) |
| 1404 |
self.watcher._sig_chld() |
| 1405 |
|
| 1406 |
callback2.assert_called_once_with(51, -8, 21) |
| 1407 |
self.assertFalse(callback1.called) |
| 1408 |
|
| 1409 |
callback2.reset_mock() |
| 1410 |
|
| 1411 |
# ensure that the child is effectively reaped |
| 1412 |
self.add_zombie(51, EXITCODE(13)) |
| 1413 |
with self.ignore_warnings: |
| 1414 |
self.watcher._sig_chld() |
| 1415 |
|
| 1416 |
self.assertFalse(callback1.called) |
| 1417 |
self.assertFalse(callback2.called) |
| 1418 |
|
| 1419 |
@waitpid_mocks |
| 1420 |
def test_sigchld_remove_handler(self, m_waitpid): |
| 1421 |
callback = mock.Mock() |
| 1422 |
|
| 1423 |
# register a child |
| 1424 |
with self.watcher: |
| 1425 |
self.running = True |
| 1426 |
self.watcher.add_child_handler(52, callback, 1984) |
| 1427 |
|
| 1428 |
self.assertFalse(callback.called) |
| 1429 |
|
| 1430 |
# unregister the child |
| 1431 |
self.watcher.remove_child_handler(52) |
| 1432 |
|
| 1433 |
self.assertFalse(callback.called) |
| 1434 |
|
| 1435 |
# child terminates (code 99) |
| 1436 |
self.running = False |
| 1437 |
self.add_zombie(52, EXITCODE(99)) |
| 1438 |
with self.ignore_warnings: |
| 1439 |
self.watcher._sig_chld() |
| 1440 |
|
| 1441 |
self.assertFalse(callback.called) |
| 1442 |
|
| 1443 |
@waitpid_mocks |
| 1444 |
def test_sigchld_unknown_status(self, m_waitpid): |
| 1445 |
callback = mock.Mock() |
| 1446 |
|
| 1447 |
# register a child |
| 1448 |
with self.watcher: |
| 1449 |
self.running = True |
| 1450 |
self.watcher.add_child_handler(53, callback, -19) |
| 1451 |
|
| 1452 |
self.assertFalse(callback.called) |
| 1453 |
|
| 1454 |
# terminate with unknown status |
| 1455 |
self.zombies[53] = 1178 |
| 1456 |
self.running = False |
| 1457 |
self.watcher._sig_chld() |
| 1458 |
|
| 1459 |
callback.assert_called_once_with(53, 1178, -19) |
| 1460 |
|
| 1461 |
callback.reset_mock() |
| 1462 |
|
| 1463 |
# ensure that the child is effectively reaped |
| 1464 |
self.add_zombie(53, EXITCODE(101)) |
| 1465 |
with self.ignore_warnings: |
| 1466 |
self.watcher._sig_chld() |
| 1467 |
|
| 1468 |
self.assertFalse(callback.called) |
| 1469 |
|
| 1470 |
@waitpid_mocks |
| 1471 |
def test_remove_child_handler(self, m_waitpid): |
| 1472 |
callback1 = mock.Mock() |
| 1473 |
callback2 = mock.Mock() |
| 1474 |
callback3 = mock.Mock() |
| 1475 |
|
| 1476 |
# register children |
| 1477 |
with self.watcher: |
| 1478 |
self.running = True |
| 1479 |
self.watcher.add_child_handler(54, callback1, 1) |
| 1480 |
self.watcher.add_child_handler(55, callback2, 2) |
| 1481 |
self.watcher.add_child_handler(56, callback3, 3) |
| 1482 |
|
| 1483 |
# remove child handler 1 |
| 1484 |
self.assertTrue(self.watcher.remove_child_handler(54)) |
| 1485 |
|
| 1486 |
# remove child handler 2 multiple times |
| 1487 |
self.assertTrue(self.watcher.remove_child_handler(55)) |
| 1488 |
self.assertFalse(self.watcher.remove_child_handler(55)) |
| 1489 |
self.assertFalse(self.watcher.remove_child_handler(55)) |
| 1490 |
|
| 1491 |
# all children terminate |
| 1492 |
self.add_zombie(54, EXITCODE(0)) |
| 1493 |
self.add_zombie(55, EXITCODE(1)) |
| 1494 |
self.add_zombie(56, EXITCODE(2)) |
| 1495 |
self.running = False |
| 1496 |
with self.ignore_warnings: |
| 1497 |
self.watcher._sig_chld() |
| 1498 |
|
| 1499 |
self.assertFalse(callback1.called) |
| 1500 |
self.assertFalse(callback2.called) |
| 1501 |
callback3.assert_called_once_with(56, 2, 3) |
| 1502 |
|
| 1503 |
@waitpid_mocks |
| 1504 |
def test_sigchld_unhandled_exception(self, m_waitpid): |
| 1505 |
callback = mock.Mock() |
| 1506 |
|
| 1507 |
# register a child |
| 1508 |
with self.watcher: |
| 1509 |
self.running = True |
| 1510 |
self.watcher.add_child_handler(57, callback) |
| 1511 |
|
| 1512 |
# raise an exception |
| 1513 |
m_waitpid.side_effect = ValueError |
| 1514 |
|
| 1515 |
with mock.patch.object(log.logger, |
| 1516 |
'error') as m_error: |
| 1517 |
|
| 1518 |
self.assertEqual(self.watcher._sig_chld(), None) |
| 1519 |
self.assertTrue(m_error.called) |
| 1520 |
|
| 1521 |
@waitpid_mocks |
| 1522 |
def test_sigchld_child_reaped_elsewhere(self, m_waitpid): |
| 1523 |
# register a child |
| 1524 |
callback = mock.Mock() |
| 1525 |
|
| 1526 |
with self.watcher: |
| 1527 |
self.running = True |
| 1528 |
self.watcher.add_child_handler(58, callback) |
| 1529 |
|
| 1530 |
self.assertFalse(callback.called) |
| 1531 |
|
| 1532 |
# child terminates |
| 1533 |
self.running = False |
| 1534 |
self.add_zombie(58, EXITCODE(4)) |
| 1535 |
|
| 1536 |
# waitpid is called elsewhere |
| 1537 |
os.waitpid(58, os.WNOHANG) |
| 1538 |
|
| 1539 |
m_waitpid.reset_mock() |
| 1540 |
|
| 1541 |
# sigchld |
| 1542 |
with self.ignore_warnings: |
| 1543 |
self.watcher._sig_chld() |
| 1544 |
|
| 1545 |
if isinstance(self.watcher, asyncio.FastChildWatcher): |
| 1546 |
# here the FastChildWatcher enters a deadlock |
| 1547 |
# (there is no way to prevent it) |
| 1548 |
self.assertFalse(callback.called) |
| 1549 |
else: |
| 1550 |
callback.assert_called_once_with(58, 255) |
| 1551 |
|
| 1552 |
@waitpid_mocks |
| 1553 |
def test_sigchld_unknown_pid_during_registration(self, m_waitpid): |
| 1554 |
# register two children |
| 1555 |
callback1 = mock.Mock() |
| 1556 |
callback2 = mock.Mock() |
| 1557 |
|
| 1558 |
with self.ignore_warnings, self.watcher: |
| 1559 |
self.running = True |
| 1560 |
# child 1 terminates |
| 1561 |
self.add_zombie(591, EXITCODE(7)) |
| 1562 |
# an unknown child terminates |
| 1563 |
self.add_zombie(593, EXITCODE(17)) |
| 1564 |
|
| 1565 |
self.watcher._sig_chld() |
| 1566 |
|
| 1567 |
self.watcher.add_child_handler(591, callback1) |
| 1568 |
self.watcher.add_child_handler(592, callback2) |
| 1569 |
|
| 1570 |
callback1.assert_called_once_with(591, 7) |
| 1571 |
self.assertFalse(callback2.called) |
| 1572 |
|
| 1573 |
@waitpid_mocks |
| 1574 |
def test_set_loop(self, m_waitpid): |
| 1575 |
# register a child |
| 1576 |
callback = mock.Mock() |
| 1577 |
|
| 1578 |
with self.watcher: |
| 1579 |
self.running = True |
| 1580 |
self.watcher.add_child_handler(60, callback) |
| 1581 |
|
| 1582 |
# attach a new loop |
| 1583 |
old_loop = self.loop |
| 1584 |
self.loop = self.new_test_loop() |
| 1585 |
patch = mock.patch.object |
| 1586 |
|
| 1587 |
with patch(old_loop, "remove_signal_handler") as m_old_remove, \ |
| 1588 |
patch(self.loop, "add_signal_handler") as m_new_add: |
| 1589 |
|
| 1590 |
self.watcher.attach_loop(self.loop) |
| 1591 |
|
| 1592 |
m_old_remove.assert_called_once_with( |
| 1593 |
signal.SIGCHLD) |
| 1594 |
m_new_add.assert_called_once_with( |
| 1595 |
signal.SIGCHLD, self.watcher._sig_chld) |
| 1596 |
|
| 1597 |
# child terminates |
| 1598 |
self.running = False |
| 1599 |
self.add_zombie(60, EXITCODE(9)) |
| 1600 |
self.watcher._sig_chld() |
| 1601 |
|
| 1602 |
callback.assert_called_once_with(60, 9) |
| 1603 |
|
| 1604 |
@waitpid_mocks |
| 1605 |
def test_set_loop_race_condition(self, m_waitpid): |
| 1606 |
# register 3 children |
| 1607 |
callback1 = mock.Mock() |
| 1608 |
callback2 = mock.Mock() |
| 1609 |
callback3 = mock.Mock() |
| 1610 |
|
| 1611 |
with self.watcher: |
| 1612 |
self.running = True |
| 1613 |
self.watcher.add_child_handler(61, callback1) |
| 1614 |
self.watcher.add_child_handler(62, callback2) |
| 1615 |
self.watcher.add_child_handler(622, callback3) |
| 1616 |
|
| 1617 |
# detach the loop |
| 1618 |
old_loop = self.loop |
| 1619 |
self.loop = None |
| 1620 |
|
| 1621 |
with mock.patch.object( |
| 1622 |
old_loop, "remove_signal_handler") as m_remove_signal_handler: |
| 1623 |
|
| 1624 |
with self.assertWarnsRegex( |
| 1625 |
RuntimeWarning, 'A loop is being detached'): |
| 1626 |
self.watcher.attach_loop(None) |
| 1627 |
|
| 1628 |
m_remove_signal_handler.assert_called_once_with( |
| 1629 |
signal.SIGCHLD) |
| 1630 |
|
| 1631 |
# child 1 & 2 terminate |
| 1632 |
self.add_zombie(61, EXITCODE(11)) |
| 1633 |
self.add_zombie(62, SIGNAL(5)) |
| 1634 |
|
| 1635 |
# SIGCHLD was not caught |
| 1636 |
self.assertFalse(callback1.called) |
| 1637 |
self.assertFalse(callback2.called) |
| 1638 |
self.assertFalse(callback3.called) |
| 1639 |
|
| 1640 |
# attach a new loop |
| 1641 |
self.loop = self.new_test_loop() |
| 1642 |
|
| 1643 |
with mock.patch.object( |
| 1644 |
self.loop, "add_signal_handler") as m_add_signal_handler: |
| 1645 |
|
| 1646 |
self.watcher.attach_loop(self.loop) |
| 1647 |
|
| 1648 |
m_add_signal_handler.assert_called_once_with( |
| 1649 |
signal.SIGCHLD, self.watcher._sig_chld) |
| 1650 |
callback1.assert_called_once_with(61, 11) # race condition! |
| 1651 |
callback2.assert_called_once_with(62, -5) # race condition! |
| 1652 |
self.assertFalse(callback3.called) |
| 1653 |
|
| 1654 |
callback1.reset_mock() |
| 1655 |
callback2.reset_mock() |
| 1656 |
|
| 1657 |
# child 3 terminates |
| 1658 |
self.running = False |
| 1659 |
self.add_zombie(622, EXITCODE(19)) |
| 1660 |
self.watcher._sig_chld() |
| 1661 |
|
| 1662 |
self.assertFalse(callback1.called) |
| 1663 |
self.assertFalse(callback2.called) |
| 1664 |
callback3.assert_called_once_with(622, 19) |
| 1665 |
|
| 1666 |
@waitpid_mocks |
| 1667 |
def test_close(self, m_waitpid): |
| 1668 |
# register two children |
| 1669 |
callback1 = mock.Mock() |
| 1670 |
|
| 1671 |
with self.watcher: |
| 1672 |
self.running = True |
| 1673 |
# child 1 terminates |
| 1674 |
self.add_zombie(63, EXITCODE(9)) |
| 1675 |
# other child terminates |
| 1676 |
self.add_zombie(65, EXITCODE(18)) |
| 1677 |
self.watcher._sig_chld() |
| 1678 |
|
| 1679 |
self.watcher.add_child_handler(63, callback1) |
| 1680 |
self.watcher.add_child_handler(64, callback1) |
| 1681 |
|
| 1682 |
self.assertEqual(len(self.watcher._callbacks), 1) |
| 1683 |
if isinstance(self.watcher, asyncio.FastChildWatcher): |
| 1684 |
self.assertEqual(len(self.watcher._zombies), 1) |
| 1685 |
|
| 1686 |
with mock.patch.object( |
| 1687 |
self.loop, |
| 1688 |
"remove_signal_handler") as m_remove_signal_handler: |
| 1689 |
|
| 1690 |
self.watcher.close() |
| 1691 |
|
| 1692 |
m_remove_signal_handler.assert_called_once_with( |
| 1693 |
signal.SIGCHLD) |
| 1694 |
self.assertFalse(self.watcher._callbacks) |
| 1695 |
if isinstance(self.watcher, asyncio.FastChildWatcher): |
| 1696 |
self.assertFalse(self.watcher._zombies) |
| 1697 |
|
| 1698 |
|
| 1699 |
class SafeChildWatcherTests (ChildWatcherTestsMixin, test_utils.TestCase): |
| 1700 |
def create_watcher(self): |
| 1701 |
with warnings.catch_warnings(): |
| 1702 |
warnings.simplefilter("ignore", DeprecationWarning) |
| 1703 |
return asyncio.SafeChildWatcher() |
| 1704 |
|
| 1705 |
|
| 1706 |
class FastChildWatcherTests (ChildWatcherTestsMixin, test_utils.TestCase): |
| 1707 |
def create_watcher(self): |
| 1708 |
with warnings.catch_warnings(): |
| 1709 |
warnings.simplefilter("ignore", DeprecationWarning) |
| 1710 |
return asyncio.FastChildWatcher() |
| 1711 |
|
| 1712 |
|
| 1713 |
class PolicyTests(unittest.TestCase): |
| 1714 |
|
| 1715 |
def create_policy(self): |
| 1716 |
return asyncio.DefaultEventLoopPolicy() |
| 1717 |
|
| 1718 |
@mock.patch('asyncio.unix_events.can_use_pidfd') |
| 1719 |
def test_get_default_child_watcher(self, m_can_use_pidfd): |
| 1720 |
m_can_use_pidfd.return_value = False |
| 1721 |
policy = self.create_policy() |
| 1722 |
self.assertIsNone(policy._watcher) |
| 1723 |
with self.assertWarns(DeprecationWarning): |
| 1724 |
watcher = policy.get_child_watcher() |
| 1725 |
self.assertIsInstance(watcher, asyncio.ThreadedChildWatcher) |
| 1726 |
|
| 1727 |
self.assertIs(policy._watcher, watcher) |
| 1728 |
with self.assertWarns(DeprecationWarning): |
| 1729 |
self.assertIs(watcher, policy.get_child_watcher()) |
| 1730 |
|
| 1731 |
m_can_use_pidfd.return_value = True |
| 1732 |
policy = self.create_policy() |
| 1733 |
self.assertIsNone(policy._watcher) |
| 1734 |
with self.assertWarns(DeprecationWarning): |
| 1735 |
watcher = policy.get_child_watcher() |
| 1736 |
self.assertIsInstance(watcher, asyncio.PidfdChildWatcher) |
| 1737 |
|
| 1738 |
self.assertIs(policy._watcher, watcher) |
| 1739 |
with self.assertWarns(DeprecationWarning): |
| 1740 |
self.assertIs(watcher, policy.get_child_watcher()) |
| 1741 |
|
| 1742 |
def test_get_child_watcher_after_set(self): |
| 1743 |
policy = self.create_policy() |
| 1744 |
with warnings.catch_warnings(): |
| 1745 |
warnings.simplefilter("ignore", DeprecationWarning) |
| 1746 |
watcher = asyncio.FastChildWatcher() |
| 1747 |
policy.set_child_watcher(watcher) |
| 1748 |
|
| 1749 |
self.assertIs(policy._watcher, watcher) |
| 1750 |
with self.assertWarns(DeprecationWarning): |
| 1751 |
self.assertIs(watcher, policy.get_child_watcher()) |
| 1752 |
|
| 1753 |
def test_get_child_watcher_thread(self): |
| 1754 |
|
| 1755 |
def f(): |
| 1756 |
policy.set_event_loop(policy.new_event_loop()) |
| 1757 |
|
| 1758 |
self.assertIsInstance(policy.get_event_loop(), |
| 1759 |
asyncio.AbstractEventLoop) |
| 1760 |
with warnings.catch_warnings(): |
| 1761 |
warnings.simplefilter("ignore", DeprecationWarning) |
| 1762 |
watcher = policy.get_child_watcher() |
| 1763 |
|
| 1764 |
self.assertIsInstance(watcher, asyncio.SafeChildWatcher) |
| 1765 |
self.assertIsNone(watcher._loop) |
| 1766 |
|
| 1767 |
policy.get_event_loop().close() |
| 1768 |
|
| 1769 |
policy = self.create_policy() |
| 1770 |
with warnings.catch_warnings(): |
| 1771 |
warnings.simplefilter("ignore", DeprecationWarning) |
| 1772 |
policy.set_child_watcher(asyncio.SafeChildWatcher()) |
| 1773 |
|
| 1774 |
th = threading.Thread(target=f) |
| 1775 |
th.start() |
| 1776 |
th.join() |
| 1777 |
|
| 1778 |
def test_child_watcher_replace_mainloop_existing(self): |
| 1779 |
policy = self.create_policy() |
| 1780 |
loop = policy.new_event_loop() |
| 1781 |
policy.set_event_loop(loop) |
| 1782 |
|
| 1783 |
# Explicitly setup SafeChildWatcher, |
| 1784 |
# default ThreadedChildWatcher has no _loop property |
| 1785 |
with warnings.catch_warnings(): |
| 1786 |
warnings.simplefilter("ignore", DeprecationWarning) |
| 1787 |
watcher = asyncio.SafeChildWatcher() |
| 1788 |
policy.set_child_watcher(watcher) |
| 1789 |
watcher.attach_loop(loop) |
| 1790 |
|
| 1791 |
self.assertIs(watcher._loop, loop) |
| 1792 |
|
| 1793 |
new_loop = policy.new_event_loop() |
| 1794 |
policy.set_event_loop(new_loop) |
| 1795 |
|
| 1796 |
self.assertIs(watcher._loop, new_loop) |
| 1797 |
|
| 1798 |
policy.set_event_loop(None) |
| 1799 |
|
| 1800 |
self.assertIs(watcher._loop, None) |
| 1801 |
|
| 1802 |
loop.close() |
| 1803 |
new_loop.close() |
| 1804 |
|
| 1805 |
|
| 1806 |
class TestFunctional(unittest.TestCase): |
| 1807 |
|
| 1808 |
def setUp(self): |
| 1809 |
self.loop = asyncio.new_event_loop() |
| 1810 |
asyncio.set_event_loop(self.loop) |
| 1811 |
|
| 1812 |
def tearDown(self): |
| 1813 |
self.loop.close() |
| 1814 |
asyncio.set_event_loop(None) |
| 1815 |
|
| 1816 |
def test_add_reader_invalid_argument(self): |
| 1817 |
def assert_raises(): |
| 1818 |
return self.assertRaisesRegex(ValueError, r'Invalid file object') |
| 1819 |
|
| 1820 |
cb = lambda: None |
| 1821 |
|
| 1822 |
with assert_raises(): |
| 1823 |
self.loop.add_reader(object(), cb) |
| 1824 |
with assert_raises(): |
| 1825 |
self.loop.add_writer(object(), cb) |
| 1826 |
|
| 1827 |
with assert_raises(): |
| 1828 |
self.loop.remove_reader(object()) |
| 1829 |
with assert_raises(): |
| 1830 |
self.loop.remove_writer(object()) |
| 1831 |
|
| 1832 |
def test_add_reader_or_writer_transport_fd(self): |
| 1833 |
def assert_raises(): |
| 1834 |
return self.assertRaisesRegex( |
| 1835 |
RuntimeError, |
| 1836 |
r'File descriptor .* is used by transport') |
| 1837 |
|
| 1838 |
async def runner(): |
| 1839 |
tr, pr = await self.loop.create_connection( |
| 1840 |
lambda: asyncio.Protocol(), sock=rsock) |
| 1841 |
|
| 1842 |
try: |
| 1843 |
cb = lambda: None |
| 1844 |
|
| 1845 |
with assert_raises(): |
| 1846 |
self.loop.add_reader(rsock, cb) |
| 1847 |
with assert_raises(): |
| 1848 |
self.loop.add_reader(rsock.fileno(), cb) |
| 1849 |
|
| 1850 |
with assert_raises(): |
| 1851 |
self.loop.remove_reader(rsock) |
| 1852 |
with assert_raises(): |
| 1853 |
self.loop.remove_reader(rsock.fileno()) |
| 1854 |
|
| 1855 |
with assert_raises(): |
| 1856 |
self.loop.add_writer(rsock, cb) |
| 1857 |
with assert_raises(): |
| 1858 |
self.loop.add_writer(rsock.fileno(), cb) |
| 1859 |
|
| 1860 |
with assert_raises(): |
| 1861 |
self.loop.remove_writer(rsock) |
| 1862 |
with assert_raises(): |
| 1863 |
self.loop.remove_writer(rsock.fileno()) |
| 1864 |
|
| 1865 |
finally: |
| 1866 |
tr.close() |
| 1867 |
|
| 1868 |
rsock, wsock = socket.socketpair() |
| 1869 |
try: |
| 1870 |
self.loop.run_until_complete(runner()) |
| 1871 |
finally: |
| 1872 |
rsock.close() |
| 1873 |
wsock.close() |
| 1874 |
|
| 1875 |
|
| 1876 |
@support.requires_fork() |
| 1877 |
class TestFork(unittest.IsolatedAsyncioTestCase): |
| 1878 |
|
| 1879 |
async def test_fork_not_share_event_loop(self): |
| 1880 |
# The forked process should not share the event loop with the parent |
| 1881 |
loop = asyncio.get_running_loop() |
| 1882 |
r, w = os.pipe() |
| 1883 |
self.addCleanup(os.close, r) |
| 1884 |
self.addCleanup(os.close, w) |
| 1885 |
pid = os.fork() |
| 1886 |
if pid == 0: |
| 1887 |
# child |
| 1888 |
try: |
| 1889 |
with self.assertWarns(DeprecationWarning): |
| 1890 |
loop = asyncio.get_event_loop_policy().get_event_loop() |
| 1891 |
os.write(w, b'LOOP:' + str(id(loop)).encode()) |
| 1892 |
except RuntimeError: |
| 1893 |
os.write(w, b'NO LOOP') |
| 1894 |
except BaseException as e: |
| 1895 |
os.write(w, b'ERROR:' + ascii(e).encode()) |
| 1896 |
finally: |
| 1897 |
os._exit(0) |
| 1898 |
else: |
| 1899 |
# parent |
| 1900 |
result = os.read(r, 100) |
| 1901 |
self.assertEqual(result[:5], b'LOOP:', result) |
| 1902 |
self.assertNotEqual(int(result[5:]), id(loop)) |
| 1903 |
wait_process(pid, exitcode=0) |
| 1904 |
|
| 1905 |
@hashlib_helper.requires_hashdigest('md5') |
| 1906 |
@support.skip_if_sanitizer("TSAN doesn't support threads after fork", thread=True) |
| 1907 |
def test_fork_signal_handling(self): |
| 1908 |
self.addCleanup(multiprocessing_cleanup_tests) |
| 1909 |
|
| 1910 |
# Sending signal to the forked process should not affect the parent |
| 1911 |
# process |
| 1912 |
ctx = multiprocessing.get_context('fork') |
| 1913 |
manager = ctx.Manager() |
| 1914 |
self.addCleanup(manager.shutdown) |
| 1915 |
child_started = manager.Event() |
| 1916 |
child_handled = manager.Event() |
| 1917 |
parent_handled = manager.Event() |
| 1918 |
|
| 1919 |
def child_main(): |
| 1920 |
def on_sigterm(*args): |
| 1921 |
child_handled.set() |
| 1922 |
sys.exit() |
| 1923 |
|
| 1924 |
signal.signal(signal.SIGTERM, on_sigterm) |
| 1925 |
child_started.set() |
| 1926 |
while True: |
| 1927 |
time.sleep(1) |
| 1928 |
|
| 1929 |
async def main(): |
| 1930 |
loop = asyncio.get_running_loop() |
| 1931 |
loop.add_signal_handler(signal.SIGTERM, lambda *args: parent_handled.set()) |
| 1932 |
|
| 1933 |
process = ctx.Process(target=child_main) |
| 1934 |
process.start() |
| 1935 |
child_started.wait() |
| 1936 |
os.kill(process.pid, signal.SIGTERM) |
| 1937 |
process.join(timeout=support.SHORT_TIMEOUT) |
| 1938 |
|
| 1939 |
async def func(): |
| 1940 |
await asyncio.sleep(0.1) |
| 1941 |
return 42 |
| 1942 |
|
| 1943 |
# Test parent's loop is still functional |
| 1944 |
self.assertEqual(await asyncio.create_task(func()), 42) |
| 1945 |
|
| 1946 |
asyncio.run(main()) |
| 1947 |
|
| 1948 |
child_handled.wait(timeout=support.SHORT_TIMEOUT) |
| 1949 |
self.assertFalse(parent_handled.is_set()) |
| 1950 |
self.assertTrue(child_handled.is_set()) |
| 1951 |
|
| 1952 |
@hashlib_helper.requires_hashdigest('md5') |
| 1953 |
@support.skip_if_sanitizer("TSAN doesn't support threads after fork", thread=True) |
| 1954 |
def test_fork_asyncio_run(self): |
| 1955 |
self.addCleanup(multiprocessing_cleanup_tests) |
| 1956 |
|
| 1957 |
ctx = multiprocessing.get_context('fork') |
| 1958 |
manager = ctx.Manager() |
| 1959 |
self.addCleanup(manager.shutdown) |
| 1960 |
result = manager.Value('i', 0) |
| 1961 |
|
| 1962 |
async def child_main(): |
| 1963 |
await asyncio.sleep(0.1) |
| 1964 |
result.value = 42 |
| 1965 |
|
| 1966 |
process = ctx.Process(target=lambda: asyncio.run(child_main())) |
| 1967 |
process.start() |
| 1968 |
process.join() |
| 1969 |
|
| 1970 |
self.assertEqual(result.value, 42) |
| 1971 |
|
| 1972 |
@hashlib_helper.requires_hashdigest('md5') |
| 1973 |
@support.skip_if_sanitizer("TSAN doesn't support threads after fork", thread=True) |
| 1974 |
def test_fork_asyncio_subprocess(self): |
| 1975 |
self.addCleanup(multiprocessing_cleanup_tests) |
| 1976 |
|
| 1977 |
ctx = multiprocessing.get_context('fork') |
| 1978 |
manager = ctx.Manager() |
| 1979 |
self.addCleanup(manager.shutdown) |
| 1980 |
result = manager.Value('i', 1) |
| 1981 |
|
| 1982 |
async def child_main(): |
| 1983 |
proc = await asyncio.create_subprocess_exec(sys.executable, '-c', 'pass') |
| 1984 |
result.value = await proc.wait() |
| 1985 |
|
| 1986 |
process = ctx.Process(target=lambda: asyncio.run(child_main())) |
| 1987 |
process.start() |
| 1988 |
process.join() |
| 1989 |
|
| 1990 |
self.assertEqual(result.value, 0) |
| 1991 |
|
| 1992 |
if __name__ == '__main__': |
| 1993 |
unittest.main() |