| 1 |
import socket |
| 2 |
import asyncio |
| 3 |
import select |
| 4 |
import sys |
| 5 |
import unittest |
| 6 |
|
| 7 |
from asyncio import proactor_events |
| 8 |
from itertools import cycle, islice |
| 9 |
from unittest.mock import Mock |
| 10 |
from test.test_asyncio import utils as test_utils |
| 11 |
from test import support |
| 12 |
from test.support import socket_helper |
| 13 |
|
| 14 |
if socket_helper.tcp_blackhole(): |
| 15 |
raise unittest.SkipTest('Not relevant to ProactorEventLoop') |
| 16 |
|
| 17 |
|
| 18 |
def tearDownModule(): |
| 19 |
asyncio.set_event_loop_policy(None) |
| 20 |
|
| 21 |
|
| 22 |
class MyProto(asyncio.Protocol): |
| 23 |
connected = None |
| 24 |
done = None |
| 25 |
|
| 26 |
def __init__(self, loop=None): |
| 27 |
self.transport = None |
| 28 |
self.state = 'INITIAL' |
| 29 |
self.nbytes = 0 |
| 30 |
if loop is not None: |
| 31 |
self.connected = loop.create_future() |
| 32 |
self.done = loop.create_future() |
| 33 |
|
| 34 |
def _assert_state(self, *expected): |
| 35 |
if self.state not in expected: |
| 36 |
raise AssertionError(f'state: {self.state!r}, expected: {expected!r}') |
| 37 |
|
| 38 |
def connection_made(self, transport): |
| 39 |
self.transport = transport |
| 40 |
self._assert_state('INITIAL') |
| 41 |
self.state = 'CONNECTED' |
| 42 |
if self.connected: |
| 43 |
self.connected.set_result(None) |
| 44 |
transport.write(b'GET / HTTP/1.0\r\nHost: example.com\r\n\r\n') |
| 45 |
|
| 46 |
def data_received(self, data): |
| 47 |
self._assert_state('CONNECTED') |
| 48 |
self.nbytes += len(data) |
| 49 |
|
| 50 |
def eof_received(self): |
| 51 |
self._assert_state('CONNECTED') |
| 52 |
self.state = 'EOF' |
| 53 |
|
| 54 |
def connection_lost(self, exc): |
| 55 |
self._assert_state('CONNECTED', 'EOF') |
| 56 |
self.state = 'CLOSED' |
| 57 |
if self.done: |
| 58 |
self.done.set_result(None) |
| 59 |
|
| 60 |
|
| 61 |
class BaseSockTestsMixin: |
| 62 |
|
| 63 |
def create_event_loop(self): |
| 64 |
raise NotImplementedError |
| 65 |
|
| 66 |
def setUp(self): |
| 67 |
self.loop = self.create_event_loop() |
| 68 |
self.set_event_loop(self.loop) |
| 69 |
super().setUp() |
| 70 |
|
| 71 |
def tearDown(self): |
| 72 |
# just in case if we have transport close callbacks |
| 73 |
if not self.loop.is_closed(): |
| 74 |
test_utils.run_briefly(self.loop) |
| 75 |
|
| 76 |
self.doCleanups() |
| 77 |
support.gc_collect() |
| 78 |
super().tearDown() |
| 79 |
|
| 80 |
def _basetest_sock_client_ops(self, httpd, sock): |
| 81 |
if not isinstance(self.loop, proactor_events.BaseProactorEventLoop): |
| 82 |
# in debug mode, socket operations must fail |
| 83 |
# if the socket is not in blocking mode |
| 84 |
self.loop.set_debug(True) |
| 85 |
sock.setblocking(True) |
| 86 |
with self.assertRaises(ValueError): |
| 87 |
self.loop.run_until_complete( |
| 88 |
self.loop.sock_connect(sock, httpd.address)) |
| 89 |
with self.assertRaises(ValueError): |
| 90 |
self.loop.run_until_complete( |
| 91 |
self.loop.sock_sendall(sock, b'GET / HTTP/1.0\r\n\r\n')) |
| 92 |
with self.assertRaises(ValueError): |
| 93 |
self.loop.run_until_complete( |
| 94 |
self.loop.sock_recv(sock, 1024)) |
| 95 |
with self.assertRaises(ValueError): |
| 96 |
self.loop.run_until_complete( |
| 97 |
self.loop.sock_recv_into(sock, bytearray())) |
| 98 |
with self.assertRaises(ValueError): |
| 99 |
self.loop.run_until_complete( |
| 100 |
self.loop.sock_accept(sock)) |
| 101 |
|
| 102 |
# test in non-blocking mode |
| 103 |
sock.setblocking(False) |
| 104 |
self.loop.run_until_complete( |
| 105 |
self.loop.sock_connect(sock, httpd.address)) |
| 106 |
self.loop.run_until_complete( |
| 107 |
self.loop.sock_sendall(sock, b'GET / HTTP/1.0\r\n\r\n')) |
| 108 |
data = self.loop.run_until_complete( |
| 109 |
self.loop.sock_recv(sock, 1024)) |
| 110 |
# consume data |
| 111 |
self.loop.run_until_complete( |
| 112 |
self.loop.sock_recv(sock, 1024)) |
| 113 |
sock.close() |
| 114 |
self.assertTrue(data.startswith(b'HTTP/1.0 200 OK')) |
| 115 |
|
| 116 |
def _basetest_sock_recv_into(self, httpd, sock): |
| 117 |
# same as _basetest_sock_client_ops, but using sock_recv_into |
| 118 |
sock.setblocking(False) |
| 119 |
self.loop.run_until_complete( |
| 120 |
self.loop.sock_connect(sock, httpd.address)) |
| 121 |
self.loop.run_until_complete( |
| 122 |
self.loop.sock_sendall(sock, b'GET / HTTP/1.0\r\n\r\n')) |
| 123 |
data = bytearray(1024) |
| 124 |
with memoryview(data) as buf: |
| 125 |
nbytes = self.loop.run_until_complete( |
| 126 |
self.loop.sock_recv_into(sock, buf[:1024])) |
| 127 |
# consume data |
| 128 |
self.loop.run_until_complete( |
| 129 |
self.loop.sock_recv_into(sock, buf[nbytes:])) |
| 130 |
sock.close() |
| 131 |
self.assertTrue(data.startswith(b'HTTP/1.0 200 OK')) |
| 132 |
|
| 133 |
def test_sock_client_ops(self): |
| 134 |
with test_utils.run_test_server() as httpd: |
| 135 |
sock = socket.socket() |
| 136 |
self._basetest_sock_client_ops(httpd, sock) |
| 137 |
sock = socket.socket() |
| 138 |
self._basetest_sock_recv_into(httpd, sock) |
| 139 |
|
| 140 |
async def _basetest_sock_recv_racing(self, httpd, sock): |
| 141 |
sock.setblocking(False) |
| 142 |
await self.loop.sock_connect(sock, httpd.address) |
| 143 |
|
| 144 |
task = asyncio.create_task(self.loop.sock_recv(sock, 1024)) |
| 145 |
await asyncio.sleep(0) |
| 146 |
task.cancel() |
| 147 |
|
| 148 |
asyncio.create_task( |
| 149 |
self.loop.sock_sendall(sock, b'GET / HTTP/1.0\r\n\r\n')) |
| 150 |
data = await self.loop.sock_recv(sock, 1024) |
| 151 |
# consume data |
| 152 |
await self.loop.sock_recv(sock, 1024) |
| 153 |
|
| 154 |
self.assertTrue(data.startswith(b'HTTP/1.0 200 OK')) |
| 155 |
|
| 156 |
async def _basetest_sock_recv_into_racing(self, httpd, sock): |
| 157 |
sock.setblocking(False) |
| 158 |
await self.loop.sock_connect(sock, httpd.address) |
| 159 |
|
| 160 |
data = bytearray(1024) |
| 161 |
with memoryview(data) as buf: |
| 162 |
task = asyncio.create_task( |
| 163 |
self.loop.sock_recv_into(sock, buf[:1024])) |
| 164 |
await asyncio.sleep(0) |
| 165 |
task.cancel() |
| 166 |
|
| 167 |
task = asyncio.create_task( |
| 168 |
self.loop.sock_sendall(sock, b'GET / HTTP/1.0\r\n\r\n')) |
| 169 |
nbytes = await self.loop.sock_recv_into(sock, buf[:1024]) |
| 170 |
# consume data |
| 171 |
await self.loop.sock_recv_into(sock, buf[nbytes:]) |
| 172 |
self.assertTrue(data.startswith(b'HTTP/1.0 200 OK')) |
| 173 |
|
| 174 |
await task |
| 175 |
|
| 176 |
async def _basetest_sock_send_racing(self, listener, sock): |
| 177 |
listener.bind(('127.0.0.1', 0)) |
| 178 |
listener.listen(1) |
| 179 |
|
| 180 |
# make connection |
| 181 |
sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 1024) |
| 182 |
sock.setblocking(False) |
| 183 |
task = asyncio.create_task( |
| 184 |
self.loop.sock_connect(sock, listener.getsockname())) |
| 185 |
await asyncio.sleep(0) |
| 186 |
server = listener.accept()[0] |
| 187 |
server.setblocking(False) |
| 188 |
|
| 189 |
with server: |
| 190 |
await task |
| 191 |
|
| 192 |
# fill the buffer until sending 5 chars would block |
| 193 |
size = 8192 |
| 194 |
while size >= 4: |
| 195 |
with self.assertRaises(BlockingIOError): |
| 196 |
while True: |
| 197 |
sock.send(b' ' * size) |
| 198 |
size = int(size / 2) |
| 199 |
|
| 200 |
# cancel a blocked sock_sendall |
| 201 |
task = asyncio.create_task( |
| 202 |
self.loop.sock_sendall(sock, b'hello')) |
| 203 |
await asyncio.sleep(0) |
| 204 |
task.cancel() |
| 205 |
|
| 206 |
# receive everything that is not a space |
| 207 |
async def recv_all(): |
| 208 |
rv = b'' |
| 209 |
while True: |
| 210 |
buf = await self.loop.sock_recv(server, 8192) |
| 211 |
if not buf: |
| 212 |
return rv |
| 213 |
rv += buf.strip() |
| 214 |
task = asyncio.create_task(recv_all()) |
| 215 |
|
| 216 |
# immediately make another sock_sendall call |
| 217 |
await self.loop.sock_sendall(sock, b'world') |
| 218 |
sock.shutdown(socket.SHUT_WR) |
| 219 |
data = await task |
| 220 |
# ProactorEventLoop could deliver hello, so endswith is necessary |
| 221 |
self.assertTrue(data.endswith(b'world')) |
| 222 |
|
| 223 |
# After the first connect attempt before the listener is ready, |
| 224 |
# the socket needs time to "recover" to make the next connect call. |
| 225 |
# On Linux, a second retry will do. On Windows, the waiting time is |
| 226 |
# unpredictable; and on FreeBSD the socket may never come back |
| 227 |
# because it's a loopback address. Here we'll just retry for a few |
| 228 |
# times, and have to skip the test if it's not working. See also: |
| 229 |
# https://stackoverflow.com/a/54437602/3316267 |
| 230 |
# https://lists.freebsd.org/pipermail/freebsd-current/2005-May/049876.html |
| 231 |
async def _basetest_sock_connect_racing(self, listener, sock): |
| 232 |
listener.bind(('127.0.0.1', 0)) |
| 233 |
addr = listener.getsockname() |
| 234 |
sock.setblocking(False) |
| 235 |
|
| 236 |
task = asyncio.create_task(self.loop.sock_connect(sock, addr)) |
| 237 |
await asyncio.sleep(0) |
| 238 |
task.cancel() |
| 239 |
|
| 240 |
listener.listen(1) |
| 241 |
|
| 242 |
skip_reason = "Max retries reached" |
| 243 |
for i in range(128): |
| 244 |
try: |
| 245 |
await self.loop.sock_connect(sock, addr) |
| 246 |
except ConnectionRefusedError as e: |
| 247 |
skip_reason = e |
| 248 |
except OSError as e: |
| 249 |
skip_reason = e |
| 250 |
|
| 251 |
# Retry only for this error: |
| 252 |
# [WinError 10022] An invalid argument was supplied |
| 253 |
if getattr(e, 'winerror', 0) != 10022: |
| 254 |
break |
| 255 |
else: |
| 256 |
# success |
| 257 |
return |
| 258 |
|
| 259 |
self.skipTest(skip_reason) |
| 260 |
|
| 261 |
async def _basetest_sock_accept_racing(self, listener, sock): |
| 262 |
# gh-153761: cancelling sock_accept() must not let a scheduled |
| 263 |
# _sock_accept run on the cancelled future. |
| 264 |
listener.setblocking(False) |
| 265 |
listener.bind(('127.0.0.1', 0)) |
| 266 |
listener.listen(1) |
| 267 |
addr = listener.getsockname() |
| 268 |
|
| 269 |
errors = [] |
| 270 |
self.loop.set_exception_handler(lambda loop, ctx: errors.append(ctx)) |
| 271 |
task = asyncio.create_task(self.loop.sock_accept(listener)) |
| 272 |
await asyncio.sleep(0) |
| 273 |
|
| 274 |
sock.connect(addr) |
| 275 |
select.select([listener], [], [], support.SHORT_TIMEOUT) |
| 276 |
|
| 277 |
self.loop.call_soon(task.cancel) |
| 278 |
await asyncio.sleep(0) |
| 279 |
await asyncio.sleep(0) |
| 280 |
|
| 281 |
with self.assertRaises(asyncio.CancelledError): |
| 282 |
await task |
| 283 |
self.assertEqual(errors, []) |
| 284 |
|
| 285 |
# The pending connection must survive |
| 286 |
conn, conn_addr = await self.loop.sock_accept(listener) |
| 287 |
with conn: |
| 288 |
self.assertEqual(conn_addr, sock.getsockname()) |
| 289 |
sock.setblocking(False) |
| 290 |
await self.loop.sock_sendall(conn, b'ping') |
| 291 |
self.assertEqual(await self.loop.sock_recv(sock, 4), b'ping') |
| 292 |
|
| 293 |
def test_sock_client_racing(self): |
| 294 |
with test_utils.run_test_server() as httpd: |
| 295 |
sock = socket.socket() |
| 296 |
with sock: |
| 297 |
self.loop.run_until_complete(asyncio.wait_for( |
| 298 |
self._basetest_sock_recv_racing(httpd, sock), 10)) |
| 299 |
sock = socket.socket() |
| 300 |
with sock: |
| 301 |
self.loop.run_until_complete(asyncio.wait_for( |
| 302 |
self._basetest_sock_recv_into_racing(httpd, sock), 10)) |
| 303 |
listener = socket.socket() |
| 304 |
sock = socket.socket() |
| 305 |
with listener, sock: |
| 306 |
self.loop.run_until_complete(asyncio.wait_for( |
| 307 |
self._basetest_sock_send_racing(listener, sock), 10)) |
| 308 |
|
| 309 |
def test_sock_client_connect_racing(self): |
| 310 |
listener = socket.socket() |
| 311 |
sock = socket.socket() |
| 312 |
with listener, sock: |
| 313 |
self.loop.run_until_complete(asyncio.wait_for( |
| 314 |
self._basetest_sock_connect_racing(listener, sock), 10)) |
| 315 |
|
| 316 |
def test_sock_accept_racing(self): |
| 317 |
if sys.platform == 'win32': |
| 318 |
if isinstance(self.loop, asyncio.ProactorEventLoop): |
| 319 |
raise unittest.SkipTest('Not relevant to ProactorEventLoop') |
| 320 |
listener = socket.socket() |
| 321 |
sock = socket.socket() |
| 322 |
with listener, sock: |
| 323 |
self.loop.run_until_complete(asyncio.wait_for( |
| 324 |
self._basetest_sock_accept_racing(listener, sock), 10)) |
| 325 |
|
| 326 |
async def _basetest_huge_content(self, address): |
| 327 |
sock = socket.socket() |
| 328 |
sock.setblocking(False) |
| 329 |
DATA_SIZE = 10_000_00 |
| 330 |
|
| 331 |
chunk = b'0123456789' * (DATA_SIZE // 10) |
| 332 |
|
| 333 |
await self.loop.sock_connect(sock, address) |
| 334 |
await self.loop.sock_sendall(sock, |
| 335 |
(b'POST /loop HTTP/1.0\r\n' + |
| 336 |
b'Content-Length: %d\r\n' % DATA_SIZE + |
| 337 |
b'\r\n')) |
| 338 |
|
| 339 |
task = asyncio.create_task(self.loop.sock_sendall(sock, chunk)) |
| 340 |
|
| 341 |
data = await self.loop.sock_recv(sock, DATA_SIZE) |
| 342 |
# HTTP headers size is less than MTU, |
| 343 |
# they are sent by the first packet always |
| 344 |
self.assertTrue(data.startswith(b'HTTP/1.0 200 OK')) |
| 345 |
while data.find(b'\r\n\r\n') == -1: |
| 346 |
data += await self.loop.sock_recv(sock, DATA_SIZE) |
| 347 |
# Strip headers |
| 348 |
headers = data[:data.index(b'\r\n\r\n') + 4] |
| 349 |
data = data[len(headers):] |
| 350 |
|
| 351 |
size = DATA_SIZE |
| 352 |
checker = cycle(b'0123456789') |
| 353 |
|
| 354 |
expected = bytes(islice(checker, len(data))) |
| 355 |
self.assertEqual(data, expected) |
| 356 |
size -= len(data) |
| 357 |
|
| 358 |
while True: |
| 359 |
data = await self.loop.sock_recv(sock, DATA_SIZE) |
| 360 |
if not data: |
| 361 |
break |
| 362 |
expected = bytes(islice(checker, len(data))) |
| 363 |
self.assertEqual(data, expected) |
| 364 |
size -= len(data) |
| 365 |
self.assertEqual(size, 0) |
| 366 |
|
| 367 |
await task |
| 368 |
sock.close() |
| 369 |
|
| 370 |
def test_huge_content(self): |
| 371 |
with test_utils.run_test_server() as httpd: |
| 372 |
self.loop.run_until_complete( |
| 373 |
self._basetest_huge_content(httpd.address)) |
| 374 |
|
| 375 |
async def _basetest_huge_content_recvinto(self, address): |
| 376 |
sock = socket.socket() |
| 377 |
sock.setblocking(False) |
| 378 |
DATA_SIZE = 10_000_00 |
| 379 |
|
| 380 |
chunk = b'0123456789' * (DATA_SIZE // 10) |
| 381 |
|
| 382 |
await self.loop.sock_connect(sock, address) |
| 383 |
await self.loop.sock_sendall(sock, |
| 384 |
(b'POST /loop HTTP/1.0\r\n' + |
| 385 |
b'Content-Length: %d\r\n' % DATA_SIZE + |
| 386 |
b'\r\n')) |
| 387 |
|
| 388 |
task = asyncio.create_task(self.loop.sock_sendall(sock, chunk)) |
| 389 |
|
| 390 |
array = bytearray(DATA_SIZE) |
| 391 |
buf = memoryview(array) |
| 392 |
|
| 393 |
nbytes = await self.loop.sock_recv_into(sock, buf) |
| 394 |
data = bytes(buf[:nbytes]) |
| 395 |
# HTTP headers size is less than MTU, |
| 396 |
# they are sent by the first packet always |
| 397 |
self.assertTrue(data.startswith(b'HTTP/1.0 200 OK')) |
| 398 |
while data.find(b'\r\n\r\n') == -1: |
| 399 |
nbytes = await self.loop.sock_recv_into(sock, buf) |
| 400 |
data = bytes(buf[:nbytes]) |
| 401 |
# Strip headers |
| 402 |
headers = data[:data.index(b'\r\n\r\n') + 4] |
| 403 |
data = data[len(headers):] |
| 404 |
|
| 405 |
size = DATA_SIZE |
| 406 |
checker = cycle(b'0123456789') |
| 407 |
|
| 408 |
expected = bytes(islice(checker, len(data))) |
| 409 |
self.assertEqual(data, expected) |
| 410 |
size -= len(data) |
| 411 |
|
| 412 |
while True: |
| 413 |
nbytes = await self.loop.sock_recv_into(sock, buf) |
| 414 |
data = buf[:nbytes] |
| 415 |
if not data: |
| 416 |
break |
| 417 |
expected = bytes(islice(checker, len(data))) |
| 418 |
self.assertEqual(data, expected) |
| 419 |
size -= len(data) |
| 420 |
self.assertEqual(size, 0) |
| 421 |
|
| 422 |
await task |
| 423 |
sock.close() |
| 424 |
|
| 425 |
def test_huge_content_recvinto(self): |
| 426 |
with test_utils.run_test_server() as httpd: |
| 427 |
self.loop.run_until_complete( |
| 428 |
self._basetest_huge_content_recvinto(httpd.address)) |
| 429 |
|
| 430 |
async def _basetest_datagram_recvfrom(self, server_address): |
| 431 |
# Happy path, sock.sendto() returns immediately |
| 432 |
data = b'\x01' * 4096 |
| 433 |
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock: |
| 434 |
sock.setblocking(False) |
| 435 |
await self.loop.sock_sendto(sock, data, server_address) |
| 436 |
received_data, from_addr = await self.loop.sock_recvfrom( |
| 437 |
sock, 4096) |
| 438 |
self.assertEqual(received_data, data) |
| 439 |
self.assertEqual(from_addr, server_address) |
| 440 |
|
| 441 |
def test_recvfrom(self): |
| 442 |
with test_utils.run_udp_echo_server() as server_address: |
| 443 |
self.loop.run_until_complete( |
| 444 |
self._basetest_datagram_recvfrom(server_address)) |
| 445 |
|
| 446 |
async def _basetest_datagram_recvfrom_into(self, server_address): |
| 447 |
# Happy path, sock.sendto() returns immediately |
| 448 |
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock: |
| 449 |
sock.setblocking(False) |
| 450 |
|
| 451 |
buf = bytearray(4096) |
| 452 |
data = b'\x01' * 4096 |
| 453 |
await self.loop.sock_sendto(sock, data, server_address) |
| 454 |
num_bytes, from_addr = await self.loop.sock_recvfrom_into( |
| 455 |
sock, buf) |
| 456 |
self.assertEqual(num_bytes, 4096) |
| 457 |
self.assertEqual(buf, data) |
| 458 |
self.assertEqual(from_addr, server_address) |
| 459 |
|
| 460 |
buf = bytearray(8192) |
| 461 |
await self.loop.sock_sendto(sock, data, server_address) |
| 462 |
num_bytes, from_addr = await self.loop.sock_recvfrom_into( |
| 463 |
sock, buf, 4096) |
| 464 |
self.assertEqual(num_bytes, 4096) |
| 465 |
self.assertEqual(buf[:4096], data[:4096]) |
| 466 |
self.assertEqual(from_addr, server_address) |
| 467 |
|
| 468 |
def test_recvfrom_into(self): |
| 469 |
with test_utils.run_udp_echo_server() as server_address: |
| 470 |
self.loop.run_until_complete( |
| 471 |
self._basetest_datagram_recvfrom_into(server_address)) |
| 472 |
|
| 473 |
async def _basetest_datagram_recvfrom_into_wrong_size(self, server_address): |
| 474 |
# Call sock_sendto() with a size larger than the buffer |
| 475 |
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock: |
| 476 |
sock.setblocking(False) |
| 477 |
|
| 478 |
buf = bytearray(5000) |
| 479 |
data = b'\x01' * 4096 |
| 480 |
wrong_size = len(buf) + 1 |
| 481 |
await self.loop.sock_sendto(sock, data, server_address) |
| 482 |
with self.assertRaises(ValueError): |
| 483 |
await self.loop.sock_recvfrom_into( |
| 484 |
sock, buf, wrong_size) |
| 485 |
|
| 486 |
size, addr = await self.loop.sock_recvfrom_into(sock, buf) |
| 487 |
self.assertEqual(buf[:size], data) |
| 488 |
|
| 489 |
def test_recvfrom_into_wrong_size(self): |
| 490 |
with test_utils.run_udp_echo_server() as server_address: |
| 491 |
self.loop.run_until_complete( |
| 492 |
self._basetest_datagram_recvfrom_into_wrong_size(server_address)) |
| 493 |
|
| 494 |
async def _basetest_datagram_sendto_blocking(self, server_address): |
| 495 |
# Sad path, sock.sendto() raises BlockingIOError |
| 496 |
# This involves patching sock.sendto() to raise BlockingIOError but |
| 497 |
# sendto() is not used by the proactor event loop |
| 498 |
data = b'\x01' * 4096 |
| 499 |
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock: |
| 500 |
sock.setblocking(False) |
| 501 |
mock_sock = Mock(sock) |
| 502 |
mock_sock.gettimeout = sock.gettimeout |
| 503 |
mock_sock.sendto.configure_mock(side_effect=BlockingIOError) |
| 504 |
mock_sock.fileno = sock.fileno |
| 505 |
self.loop.call_soon( |
| 506 |
lambda: setattr(mock_sock, 'sendto', sock.sendto) |
| 507 |
) |
| 508 |
await self.loop.sock_sendto(mock_sock, data, server_address) |
| 509 |
|
| 510 |
received_data, from_addr = await self.loop.sock_recvfrom( |
| 511 |
sock, 4096) |
| 512 |
self.assertEqual(received_data, data) |
| 513 |
self.assertEqual(from_addr, server_address) |
| 514 |
|
| 515 |
def test_sendto_blocking(self): |
| 516 |
if sys.platform == 'win32': |
| 517 |
if isinstance(self.loop, asyncio.ProactorEventLoop): |
| 518 |
raise unittest.SkipTest('Not relevant to ProactorEventLoop') |
| 519 |
|
| 520 |
with test_utils.run_udp_echo_server() as server_address: |
| 521 |
self.loop.run_until_complete( |
| 522 |
self._basetest_datagram_sendto_blocking(server_address)) |
| 523 |
|
| 524 |
@socket_helper.skip_unless_bind_unix_socket |
| 525 |
def test_unix_sock_client_ops(self): |
| 526 |
with test_utils.run_test_unix_server() as httpd: |
| 527 |
sock = socket.socket(socket.AF_UNIX) |
| 528 |
self._basetest_sock_client_ops(httpd, sock) |
| 529 |
sock = socket.socket(socket.AF_UNIX) |
| 530 |
self._basetest_sock_recv_into(httpd, sock) |
| 531 |
|
| 532 |
def test_sock_client_fail(self): |
| 533 |
# Make sure that we will get an unused port |
| 534 |
address = None |
| 535 |
try: |
| 536 |
s = socket.socket() |
| 537 |
s.bind(('127.0.0.1', 0)) |
| 538 |
address = s.getsockname() |
| 539 |
finally: |
| 540 |
s.close() |
| 541 |
|
| 542 |
sock = socket.socket() |
| 543 |
sock.setblocking(False) |
| 544 |
with self.assertRaises(ConnectionRefusedError): |
| 545 |
self.loop.run_until_complete( |
| 546 |
self.loop.sock_connect(sock, address)) |
| 547 |
sock.close() |
| 548 |
|
| 549 |
def test_sock_accept(self): |
| 550 |
listener = socket.socket() |
| 551 |
listener.setblocking(False) |
| 552 |
listener.bind(('127.0.0.1', 0)) |
| 553 |
listener.listen(1) |
| 554 |
client = socket.socket() |
| 555 |
client.connect(listener.getsockname()) |
| 556 |
|
| 557 |
f = self.loop.sock_accept(listener) |
| 558 |
conn, addr = self.loop.run_until_complete(f) |
| 559 |
self.assertEqual(conn.gettimeout(), 0) |
| 560 |
self.assertEqual(addr, client.getsockname()) |
| 561 |
self.assertEqual(client.getpeername(), listener.getsockname()) |
| 562 |
client.close() |
| 563 |
conn.close() |
| 564 |
listener.close() |
| 565 |
|
| 566 |
def test_cancel_sock_accept(self): |
| 567 |
listener = socket.socket() |
| 568 |
listener.setblocking(False) |
| 569 |
listener.bind(('127.0.0.1', 0)) |
| 570 |
listener.listen(1) |
| 571 |
sockaddr = listener.getsockname() |
| 572 |
f = asyncio.wait_for(self.loop.sock_accept(listener), 0.1) |
| 573 |
with self.assertRaises(asyncio.TimeoutError): |
| 574 |
self.loop.run_until_complete(f) |
| 575 |
|
| 576 |
listener.close() |
| 577 |
client = socket.socket() |
| 578 |
client.setblocking(False) |
| 579 |
f = self.loop.sock_connect(client, sockaddr) |
| 580 |
with self.assertRaises(ConnectionRefusedError): |
| 581 |
self.loop.run_until_complete(f) |
| 582 |
|
| 583 |
client.close() |
| 584 |
|
| 585 |
def test_create_connection_sock(self): |
| 586 |
with test_utils.run_test_server() as httpd: |
| 587 |
sock = None |
| 588 |
infos = self.loop.run_until_complete( |
| 589 |
self.loop.getaddrinfo( |
| 590 |
*httpd.address, type=socket.SOCK_STREAM)) |
| 591 |
for family, type, proto, cname, address in infos: |
| 592 |
try: |
| 593 |
sock = socket.socket(family=family, type=type, proto=proto) |
| 594 |
sock.setblocking(False) |
| 595 |
self.loop.run_until_complete( |
| 596 |
self.loop.sock_connect(sock, address)) |
| 597 |
except BaseException: |
| 598 |
pass |
| 599 |
else: |
| 600 |
break |
| 601 |
else: |
| 602 |
self.fail('Can not create socket.') |
| 603 |
|
| 604 |
f = self.loop.create_connection( |
| 605 |
lambda: MyProto(loop=self.loop), sock=sock) |
| 606 |
tr, pr = self.loop.run_until_complete(f) |
| 607 |
self.assertIsInstance(tr, asyncio.Transport) |
| 608 |
self.assertIsInstance(pr, asyncio.Protocol) |
| 609 |
self.loop.run_until_complete(pr.done) |
| 610 |
self.assertGreater(pr.nbytes, 0) |
| 611 |
tr.close() |
| 612 |
|
| 613 |
|
| 614 |
if sys.platform == 'win32': |
| 615 |
|
| 616 |
class SelectEventLoopTests(BaseSockTestsMixin, |
| 617 |
test_utils.TestCase): |
| 618 |
|
| 619 |
def create_event_loop(self): |
| 620 |
return asyncio.SelectorEventLoop() |
| 621 |
|
| 622 |
|
| 623 |
class ProactorEventLoopTests(BaseSockTestsMixin, |
| 624 |
test_utils.TestCase): |
| 625 |
|
| 626 |
def create_event_loop(self): |
| 627 |
return asyncio.ProactorEventLoop() |
| 628 |
|
| 629 |
|
| 630 |
async def _basetest_datagram_send_to_non_listening_address(self, |
| 631 |
recvfrom): |
| 632 |
# see: |
| 633 |
# https://github.com/python/cpython/issues/91227 |
| 634 |
# https://github.com/python/cpython/issues/88906 |
| 635 |
# https://bugs.python.org/issue47071 |
| 636 |
# https://bugs.python.org/issue44743 |
| 637 |
# The Proactor event loop would fail to receive datagram messages |
| 638 |
# after sending a message to an address that wasn't listening. |
| 639 |
|
| 640 |
def create_socket(): |
| 641 |
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
| 642 |
sock.setblocking(False) |
| 643 |
sock.bind(('127.0.0.1', 0)) |
| 644 |
return sock |
| 645 |
|
| 646 |
socket_1 = create_socket() |
| 647 |
addr_1 = socket_1.getsockname() |
| 648 |
|
| 649 |
socket_2 = create_socket() |
| 650 |
addr_2 = socket_2.getsockname() |
| 651 |
|
| 652 |
# creating and immediately closing this to try to get an address |
| 653 |
# that is not listening |
| 654 |
socket_3 = create_socket() |
| 655 |
addr_3 = socket_3.getsockname() |
| 656 |
socket_3.shutdown(socket.SHUT_RDWR) |
| 657 |
socket_3.close() |
| 658 |
|
| 659 |
socket_1_recv_task = self.loop.create_task(recvfrom(socket_1)) |
| 660 |
socket_2_recv_task = self.loop.create_task(recvfrom(socket_2)) |
| 661 |
await asyncio.sleep(0) |
| 662 |
|
| 663 |
await self.loop.sock_sendto(socket_1, b'a', addr_2) |
| 664 |
self.assertEqual(await socket_2_recv_task, b'a') |
| 665 |
|
| 666 |
await self.loop.sock_sendto(socket_2, b'b', addr_1) |
| 667 |
self.assertEqual(await socket_1_recv_task, b'b') |
| 668 |
socket_1_recv_task = self.loop.create_task(recvfrom(socket_1)) |
| 669 |
await asyncio.sleep(0) |
| 670 |
|
| 671 |
# this should send to an address that isn't listening |
| 672 |
await self.loop.sock_sendto(socket_1, b'c', addr_3) |
| 673 |
self.assertEqual(await socket_1_recv_task, b'') |
| 674 |
socket_1_recv_task = self.loop.create_task(recvfrom(socket_1)) |
| 675 |
await asyncio.sleep(0) |
| 676 |
|
| 677 |
# socket 1 should still be able to receive messages after sending |
| 678 |
# to an address that wasn't listening |
| 679 |
socket_2.sendto(b'd', addr_1) |
| 680 |
self.assertEqual(await socket_1_recv_task, b'd') |
| 681 |
|
| 682 |
socket_1.shutdown(socket.SHUT_RDWR) |
| 683 |
socket_1.close() |
| 684 |
socket_2.shutdown(socket.SHUT_RDWR) |
| 685 |
socket_2.close() |
| 686 |
|
| 687 |
|
| 688 |
def test_datagram_send_to_non_listening_address_recvfrom(self): |
| 689 |
async def recvfrom(socket): |
| 690 |
data, _ = await self.loop.sock_recvfrom(socket, 4096) |
| 691 |
return data |
| 692 |
|
| 693 |
self.loop.run_until_complete( |
| 694 |
self._basetest_datagram_send_to_non_listening_address( |
| 695 |
recvfrom)) |
| 696 |
|
| 697 |
|
| 698 |
def test_datagram_send_to_non_listening_address_recvfrom_into(self): |
| 699 |
async def recvfrom_into(socket): |
| 700 |
buf = bytearray(4096) |
| 701 |
length, _ = await self.loop.sock_recvfrom_into(socket, buf, |
| 702 |
4096) |
| 703 |
return buf[:length] |
| 704 |
|
| 705 |
self.loop.run_until_complete( |
| 706 |
self._basetest_datagram_send_to_non_listening_address( |
| 707 |
recvfrom_into)) |
| 708 |
|
| 709 |
else: |
| 710 |
import selectors |
| 711 |
|
| 712 |
if hasattr(selectors, 'KqueueSelector'): |
| 713 |
class KqueueEventLoopTests(BaseSockTestsMixin, |
| 714 |
test_utils.TestCase): |
| 715 |
|
| 716 |
def create_event_loop(self): |
| 717 |
return asyncio.SelectorEventLoop( |
| 718 |
selectors.KqueueSelector()) |
| 719 |
|
| 720 |
if hasattr(selectors, 'EpollSelector'): |
| 721 |
class EPollEventLoopTests(BaseSockTestsMixin, |
| 722 |
test_utils.TestCase): |
| 723 |
|
| 724 |
def create_event_loop(self): |
| 725 |
return asyncio.SelectorEventLoop(selectors.EpollSelector()) |
| 726 |
|
| 727 |
if hasattr(selectors, 'PollSelector'): |
| 728 |
class PollEventLoopTests(BaseSockTestsMixin, |
| 729 |
test_utils.TestCase): |
| 730 |
|
| 731 |
def create_event_loop(self): |
| 732 |
return asyncio.SelectorEventLoop(selectors.PollSelector()) |
| 733 |
|
| 734 |
# Should always exist. |
| 735 |
class SelectEventLoopTests(BaseSockTestsMixin, |
| 736 |
test_utils.TestCase): |
| 737 |
|
| 738 |
def create_event_loop(self): |
| 739 |
return asyncio.SelectorEventLoop(selectors.SelectSelector()) |
| 740 |
|
| 741 |
|
| 742 |
if __name__ == '__main__': |
| 743 |
unittest.main() |