| 1 |
import unittest |
| 2 |
from unittest import mock |
| 3 |
from test import support |
| 4 |
from test.support import ( |
| 5 |
cpython_only, is_apple, os_helper, refleak_helper, socket_helper, threading_helper |
| 6 |
) |
| 7 |
from test.support.import_helper import ensure_lazy_imports |
| 8 |
import _thread as thread |
| 9 |
import array |
| 10 |
import contextlib |
| 11 |
import errno |
| 12 |
import gc |
| 13 |
import io |
| 14 |
import itertools |
| 15 |
import math |
| 16 |
import os |
| 17 |
import pickle |
| 18 |
import platform |
| 19 |
import queue |
| 20 |
import random |
| 21 |
import re |
| 22 |
import select |
| 23 |
import signal |
| 24 |
import socket |
| 25 |
import string |
| 26 |
import struct |
| 27 |
import sys |
| 28 |
import tempfile |
| 29 |
import threading |
| 30 |
import time |
| 31 |
import traceback |
| 32 |
import warnings |
| 33 |
from weakref import proxy |
| 34 |
try: |
| 35 |
import multiprocessing |
| 36 |
except ImportError: |
| 37 |
multiprocessing = False |
| 38 |
try: |
| 39 |
import fcntl |
| 40 |
except ImportError: |
| 41 |
fcntl = None |
| 42 |
try: |
| 43 |
import _testcapi |
| 44 |
except ImportError: |
| 45 |
_testcapi = None |
| 46 |
|
| 47 |
support.requires_working_socket(module=True) |
| 48 |
|
| 49 |
HOST = socket_helper.HOST |
| 50 |
# test unicode string and carriage return |
| 51 |
MSG = 'Michael Gilfix was here\u1234\r\n'.encode('utf-8') |
| 52 |
|
| 53 |
VSOCKPORT = 1234 |
| 54 |
AIX = platform.system() == "AIX" |
| 55 |
SOLARIS = sys.platform.startswith("sunos") |
| 56 |
WSL = "microsoft-standard-WSL" in platform.release() |
| 57 |
|
| 58 |
try: |
| 59 |
import _socket |
| 60 |
except ImportError: |
| 61 |
_socket = None |
| 62 |
|
| 63 |
def skipForRefleakHuntinIf(condition, issueref): |
| 64 |
if not condition: |
| 65 |
def decorator(f): |
| 66 |
f.client_skip = lambda f: f |
| 67 |
return f |
| 68 |
|
| 69 |
else: |
| 70 |
def decorator(f): |
| 71 |
@contextlib.wraps(f) |
| 72 |
def wrapper(*args, **kwds): |
| 73 |
if refleak_helper.hunting_for_refleaks(): |
| 74 |
raise unittest.SkipTest(f"ignore while hunting for refleaks, see {issueref}") |
| 75 |
|
| 76 |
return f(*args, **kwds) |
| 77 |
|
| 78 |
def client_skip(f): |
| 79 |
@contextlib.wraps(f) |
| 80 |
def wrapper(*args, **kwds): |
| 81 |
if refleak_helper.hunting_for_refleaks(): |
| 82 |
return |
| 83 |
|
| 84 |
return f(*args, **kwds) |
| 85 |
|
| 86 |
return wrapper |
| 87 |
wrapper.client_skip = client_skip |
| 88 |
return wrapper |
| 89 |
|
| 90 |
return decorator |
| 91 |
|
| 92 |
def get_cid(): |
| 93 |
if fcntl is None: |
| 94 |
return None |
| 95 |
if not hasattr(socket, 'IOCTL_VM_SOCKETS_GET_LOCAL_CID'): |
| 96 |
return None |
| 97 |
try: |
| 98 |
with open("/dev/vsock", "rb") as f: |
| 99 |
r = fcntl.ioctl(f, socket.IOCTL_VM_SOCKETS_GET_LOCAL_CID, " ") |
| 100 |
except OSError: |
| 101 |
return None |
| 102 |
else: |
| 103 |
return struct.unpack("I", r)[0] |
| 104 |
|
| 105 |
def _have_socket_can(): |
| 106 |
"""Check whether CAN sockets are supported on this host.""" |
| 107 |
try: |
| 108 |
s = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) |
| 109 |
except (AttributeError, OSError): |
| 110 |
return False |
| 111 |
else: |
| 112 |
s.close() |
| 113 |
return True |
| 114 |
|
| 115 |
def _have_socket_can_isotp(): |
| 116 |
"""Check whether CAN ISOTP sockets are supported on this host.""" |
| 117 |
try: |
| 118 |
s = socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_ISOTP) |
| 119 |
except (AttributeError, OSError): |
| 120 |
return False |
| 121 |
else: |
| 122 |
s.close() |
| 123 |
return True |
| 124 |
|
| 125 |
def _have_socket_can_j1939(): |
| 126 |
"""Check whether CAN J1939 sockets are supported on this host.""" |
| 127 |
try: |
| 128 |
s = socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_J1939) |
| 129 |
except (AttributeError, OSError): |
| 130 |
return False |
| 131 |
else: |
| 132 |
s.close() |
| 133 |
return True |
| 134 |
|
| 135 |
def _have_socket_rds(): |
| 136 |
"""Check whether RDS sockets are supported on this host.""" |
| 137 |
try: |
| 138 |
s = socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0) |
| 139 |
except (AttributeError, OSError): |
| 140 |
return False |
| 141 |
else: |
| 142 |
s.close() |
| 143 |
return True |
| 144 |
|
| 145 |
def _have_socket_alg(): |
| 146 |
"""Check whether AF_ALG sockets are supported on this host.""" |
| 147 |
try: |
| 148 |
s = socket.socket(socket.AF_ALG, socket.SOCK_SEQPACKET, 0) |
| 149 |
except (AttributeError, OSError): |
| 150 |
return False |
| 151 |
else: |
| 152 |
s.close() |
| 153 |
return True |
| 154 |
|
| 155 |
def _have_socket_qipcrtr(): |
| 156 |
"""Check whether AF_QIPCRTR sockets are supported on this host.""" |
| 157 |
try: |
| 158 |
s = socket.socket(socket.AF_QIPCRTR, socket.SOCK_DGRAM, 0) |
| 159 |
except (AttributeError, OSError): |
| 160 |
return False |
| 161 |
else: |
| 162 |
s.close() |
| 163 |
return True |
| 164 |
|
| 165 |
def _have_socket_vsock(): |
| 166 |
"""Check whether AF_VSOCK sockets are supported on this host.""" |
| 167 |
cid = get_cid() |
| 168 |
return (cid is not None) |
| 169 |
|
| 170 |
|
| 171 |
def _have_socket_bluetooth(): |
| 172 |
"""Check whether AF_BLUETOOTH sockets are supported on this host.""" |
| 173 |
try: |
| 174 |
# RFCOMM is supported by all platforms with bluetooth support. Windows |
| 175 |
# does not support omitting the protocol. |
| 176 |
s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM) |
| 177 |
except (AttributeError, OSError): |
| 178 |
return False |
| 179 |
else: |
| 180 |
s.close() |
| 181 |
return True |
| 182 |
|
| 183 |
|
| 184 |
def _have_socket_bluetooth_l2cap(): |
| 185 |
"""Check whether BTPROTO_L2CAP sockets are supported on this host.""" |
| 186 |
try: |
| 187 |
s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_SEQPACKET, socket.BTPROTO_L2CAP) |
| 188 |
except (AttributeError, OSError): |
| 189 |
return False |
| 190 |
else: |
| 191 |
s.close() |
| 192 |
return True |
| 193 |
|
| 194 |
|
| 195 |
def _have_socket_hyperv(): |
| 196 |
"""Check whether AF_HYPERV sockets are supported on this host.""" |
| 197 |
try: |
| 198 |
s = socket.socket(socket.AF_HYPERV, socket.SOCK_STREAM, socket.HV_PROTOCOL_RAW) |
| 199 |
except (AttributeError, OSError): |
| 200 |
return False |
| 201 |
else: |
| 202 |
s.close() |
| 203 |
return True |
| 204 |
|
| 205 |
|
| 206 |
def _have_udp_lite(): |
| 207 |
if not hasattr(socket, "IPPROTO_UDPLITE"): |
| 208 |
return False |
| 209 |
# Older Android versions block UDPLITE with SELinux. |
| 210 |
if support.is_android and platform.android_ver().api_level < 29: |
| 211 |
return False |
| 212 |
|
| 213 |
try: |
| 214 |
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDPLITE) |
| 215 |
except OSError as exc: |
| 216 |
# Linux 7.1 removed UDP Lite support |
| 217 |
if exc.errno == errno.EPROTONOSUPPORT: |
| 218 |
return False |
| 219 |
raise |
| 220 |
sock.close() |
| 221 |
|
| 222 |
return True |
| 223 |
|
| 224 |
|
| 225 |
@contextlib.contextmanager |
| 226 |
def socket_setdefaulttimeout(timeout): |
| 227 |
old_timeout = socket.getdefaulttimeout() |
| 228 |
try: |
| 229 |
socket.setdefaulttimeout(timeout) |
| 230 |
yield |
| 231 |
finally: |
| 232 |
socket.setdefaulttimeout(old_timeout) |
| 233 |
|
| 234 |
|
| 235 |
@contextlib.contextmanager |
| 236 |
def downgrade_malformed_data_warning(): |
| 237 |
# This warning happens on macos and win, but does not always happen on linux. |
| 238 |
if sys.platform not in {"win32", "darwin"}: |
| 239 |
yield |
| 240 |
return |
| 241 |
|
| 242 |
with warnings.catch_warnings(): |
| 243 |
# TODO: gh-110012, we should investigate why this warning is happening |
| 244 |
# and fix it properly. |
| 245 |
warnings.filterwarnings( |
| 246 |
action="always", |
| 247 |
message="received malformed or improperly-truncated ancillary data", |
| 248 |
category=RuntimeWarning, |
| 249 |
) |
| 250 |
yield |
| 251 |
|
| 252 |
|
| 253 |
HAVE_SOCKET_CAN = _have_socket_can() |
| 254 |
|
| 255 |
HAVE_SOCKET_CAN_ISOTP = _have_socket_can_isotp() |
| 256 |
|
| 257 |
HAVE_SOCKET_CAN_J1939 = _have_socket_can_j1939() |
| 258 |
|
| 259 |
HAVE_SOCKET_RDS = _have_socket_rds() |
| 260 |
|
| 261 |
HAVE_SOCKET_ALG = _have_socket_alg() |
| 262 |
|
| 263 |
HAVE_SOCKET_QIPCRTR = _have_socket_qipcrtr() |
| 264 |
|
| 265 |
HAVE_SOCKET_VSOCK = _have_socket_vsock() |
| 266 |
|
| 267 |
HAVE_SOCKET_UDPLITE = _have_udp_lite() |
| 268 |
|
| 269 |
HAVE_SOCKET_BLUETOOTH = _have_socket_bluetooth() |
| 270 |
|
| 271 |
HAVE_SOCKET_BLUETOOTH_L2CAP = _have_socket_bluetooth_l2cap() |
| 272 |
|
| 273 |
HAVE_SOCKET_HYPERV = _have_socket_hyperv() |
| 274 |
|
| 275 |
# Size in bytes of the int type |
| 276 |
SIZEOF_INT = array.array("i").itemsize |
| 277 |
|
| 278 |
class TestLazyImport(unittest.TestCase): |
| 279 |
@cpython_only |
| 280 |
def test_lazy_import(self): |
| 281 |
ensure_lazy_imports("socket", {"array", "selectors"}) |
| 282 |
|
| 283 |
|
| 284 |
class SocketTCPTest(unittest.TestCase): |
| 285 |
|
| 286 |
def setUp(self): |
| 287 |
self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 288 |
self.port = socket_helper.bind_port(self.serv) |
| 289 |
self.serv.listen() |
| 290 |
|
| 291 |
def tearDown(self): |
| 292 |
self.serv.close() |
| 293 |
self.serv = None |
| 294 |
|
| 295 |
class SocketUDPTest(unittest.TestCase): |
| 296 |
|
| 297 |
def setUp(self): |
| 298 |
self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
| 299 |
self.port = socket_helper.bind_port(self.serv) |
| 300 |
|
| 301 |
def tearDown(self): |
| 302 |
self.serv.close() |
| 303 |
self.serv = None |
| 304 |
|
| 305 |
class SocketUDPLITETest(SocketUDPTest): |
| 306 |
|
| 307 |
def setUp(self): |
| 308 |
self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDPLITE) |
| 309 |
self.port = socket_helper.bind_port(self.serv) |
| 310 |
|
| 311 |
|
| 312 |
class SocketCANTest(unittest.TestCase): |
| 313 |
|
| 314 |
"""To be able to run this test, a `vcan0` CAN interface can be created with |
| 315 |
the following commands: |
| 316 |
# modprobe vcan |
| 317 |
# ip link add dev vcan0 type vcan |
| 318 |
# ip link set up vcan0 |
| 319 |
""" |
| 320 |
interface = 'vcan0' |
| 321 |
bufsize = 128 |
| 322 |
|
| 323 |
"""The CAN frame structure is defined in <linux/can.h>: |
| 324 |
|
| 325 |
struct can_frame { |
| 326 |
canid_t can_id; /* 32 bit CAN_ID + EFF/RTR/ERR flags */ |
| 327 |
__u8 can_dlc; /* data length code: 0 .. 8 */ |
| 328 |
__u8 data[8] __attribute__((aligned(8))); |
| 329 |
}; |
| 330 |
""" |
| 331 |
can_frame_fmt = "=IB3x8s" |
| 332 |
can_frame_size = struct.calcsize(can_frame_fmt) |
| 333 |
|
| 334 |
"""The Broadcast Management Command frame structure is defined |
| 335 |
in <linux/can/bcm.h>: |
| 336 |
|
| 337 |
struct bcm_msg_head { |
| 338 |
__u32 opcode; |
| 339 |
__u32 flags; |
| 340 |
__u32 count; |
| 341 |
struct timeval ival1, ival2; |
| 342 |
canid_t can_id; |
| 343 |
__u32 nframes; |
| 344 |
struct can_frame frames[0]; |
| 345 |
} |
| 346 |
|
| 347 |
`bcm_msg_head` must be 8 bytes aligned because of the `frames` member (see |
| 348 |
`struct can_frame` definition). Must use native not standard types for packing. |
| 349 |
""" |
| 350 |
bcm_cmd_msg_fmt = "@3I4l2I" |
| 351 |
bcm_cmd_msg_fmt += "x" * (struct.calcsize(bcm_cmd_msg_fmt) % 8) |
| 352 |
|
| 353 |
def setUp(self): |
| 354 |
self.s = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) |
| 355 |
self.addCleanup(self.s.close) |
| 356 |
try: |
| 357 |
self.s.bind((self.interface,)) |
| 358 |
except OSError: |
| 359 |
self.skipTest('network interface `%s` does not exist' % |
| 360 |
self.interface) |
| 361 |
|
| 362 |
|
| 363 |
class SocketRDSTest(unittest.TestCase): |
| 364 |
|
| 365 |
"""To be able to run this test, the `rds` kernel module must be loaded: |
| 366 |
# modprobe rds |
| 367 |
""" |
| 368 |
bufsize = 8192 |
| 369 |
|
| 370 |
def setUp(self): |
| 371 |
self.serv = socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0) |
| 372 |
self.addCleanup(self.serv.close) |
| 373 |
try: |
| 374 |
self.port = socket_helper.bind_port(self.serv) |
| 375 |
except OSError: |
| 376 |
self.skipTest('unable to bind RDS socket') |
| 377 |
|
| 378 |
|
| 379 |
class ThreadableTest: |
| 380 |
"""Threadable Test class |
| 381 |
|
| 382 |
The ThreadableTest class makes it easy to create a threaded |
| 383 |
client/server pair from an existing unit test. To create a |
| 384 |
new threaded class from an existing unit test, use multiple |
| 385 |
inheritance: |
| 386 |
|
| 387 |
class NewClass (OldClass, ThreadableTest): |
| 388 |
pass |
| 389 |
|
| 390 |
This class defines two new fixture functions with obvious |
| 391 |
purposes for overriding: |
| 392 |
|
| 393 |
clientSetUp () |
| 394 |
clientTearDown () |
| 395 |
|
| 396 |
Any new test functions within the class must then define |
| 397 |
tests in pairs, where the test name is preceded with a |
| 398 |
'_' to indicate the client portion of the test. Ex: |
| 399 |
|
| 400 |
def testFoo(self): |
| 401 |
# Server portion |
| 402 |
|
| 403 |
def _testFoo(self): |
| 404 |
# Client portion |
| 405 |
|
| 406 |
Any exceptions raised by the clients during their tests |
| 407 |
are caught and transferred to the main thread to alert |
| 408 |
the testing framework. |
| 409 |
|
| 410 |
Note, the server setup function cannot call any blocking |
| 411 |
functions that rely on the client thread during setup, |
| 412 |
unless serverExplicitReady() is called just before |
| 413 |
the blocking call (such as in setting up a client/server |
| 414 |
connection and performing the accept() in setUp(). |
| 415 |
""" |
| 416 |
|
| 417 |
def __init__(self): |
| 418 |
# Swap the true setup function |
| 419 |
self.__setUp = self.setUp |
| 420 |
self.setUp = self._setUp |
| 421 |
|
| 422 |
def serverExplicitReady(self): |
| 423 |
"""This method allows the server to explicitly indicate that |
| 424 |
it wants the client thread to proceed. This is useful if the |
| 425 |
server is about to execute a blocking routine that is |
| 426 |
dependent upon the client thread during its setup routine.""" |
| 427 |
self.server_ready.set() |
| 428 |
|
| 429 |
def _setUp(self): |
| 430 |
self.enterContext(threading_helper.wait_threads_exit()) |
| 431 |
|
| 432 |
self.server_ready = threading.Event() |
| 433 |
self.client_ready = threading.Event() |
| 434 |
self.done = threading.Event() |
| 435 |
self.queue = queue.Queue(1) |
| 436 |
self.server_crashed = False |
| 437 |
|
| 438 |
def raise_queued_exception(): |
| 439 |
if self.queue.qsize(): |
| 440 |
raise self.queue.get() |
| 441 |
self.addCleanup(raise_queued_exception) |
| 442 |
|
| 443 |
# Do some munging to start the client test. |
| 444 |
methodname = self.id() |
| 445 |
i = methodname.rfind('.') |
| 446 |
methodname = methodname[i+1:] |
| 447 |
test_method = getattr(self, '_' + methodname) |
| 448 |
self.client_thread = thread.start_new_thread( |
| 449 |
self.clientRun, (test_method,)) |
| 450 |
|
| 451 |
try: |
| 452 |
self.__setUp() |
| 453 |
except: |
| 454 |
self.server_crashed = True |
| 455 |
raise |
| 456 |
finally: |
| 457 |
self.server_ready.set() |
| 458 |
self.client_ready.wait() |
| 459 |
self.addCleanup(self.done.wait) |
| 460 |
|
| 461 |
def clientRun(self, test_func): |
| 462 |
self.server_ready.wait() |
| 463 |
try: |
| 464 |
self.clientSetUp() |
| 465 |
except BaseException as e: |
| 466 |
self.queue.put(e) |
| 467 |
self.clientTearDown() |
| 468 |
return |
| 469 |
finally: |
| 470 |
self.client_ready.set() |
| 471 |
if self.server_crashed: |
| 472 |
self.clientTearDown() |
| 473 |
return |
| 474 |
if not hasattr(test_func, '__call__'): |
| 475 |
raise TypeError("test_func must be a callable function") |
| 476 |
try: |
| 477 |
test_func() |
| 478 |
except BaseException as e: |
| 479 |
self.queue.put(e) |
| 480 |
finally: |
| 481 |
self.clientTearDown() |
| 482 |
|
| 483 |
def clientSetUp(self): |
| 484 |
raise NotImplementedError("clientSetUp must be implemented.") |
| 485 |
|
| 486 |
def clientTearDown(self): |
| 487 |
self.done.set() |
| 488 |
thread.exit() |
| 489 |
|
| 490 |
class ThreadedTCPSocketTest(SocketTCPTest, ThreadableTest): |
| 491 |
|
| 492 |
def __init__(self, methodName='runTest'): |
| 493 |
SocketTCPTest.__init__(self, methodName=methodName) |
| 494 |
ThreadableTest.__init__(self) |
| 495 |
|
| 496 |
def clientSetUp(self): |
| 497 |
self.cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 498 |
|
| 499 |
def clientTearDown(self): |
| 500 |
self.cli.close() |
| 501 |
self.cli = None |
| 502 |
ThreadableTest.clientTearDown(self) |
| 503 |
|
| 504 |
class ThreadedUDPSocketTest(SocketUDPTest, ThreadableTest): |
| 505 |
|
| 506 |
def __init__(self, methodName='runTest'): |
| 507 |
SocketUDPTest.__init__(self, methodName=methodName) |
| 508 |
ThreadableTest.__init__(self) |
| 509 |
|
| 510 |
def clientSetUp(self): |
| 511 |
self.cli = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
| 512 |
|
| 513 |
def clientTearDown(self): |
| 514 |
self.cli.close() |
| 515 |
self.cli = None |
| 516 |
ThreadableTest.clientTearDown(self) |
| 517 |
|
| 518 |
@unittest.skipUnless(HAVE_SOCKET_UDPLITE, |
| 519 |
'UDPLITE sockets required for this test.') |
| 520 |
class ThreadedUDPLITESocketTest(SocketUDPLITETest, ThreadableTest): |
| 521 |
|
| 522 |
def __init__(self, methodName='runTest'): |
| 523 |
SocketUDPLITETest.__init__(self, methodName=methodName) |
| 524 |
ThreadableTest.__init__(self) |
| 525 |
|
| 526 |
def clientSetUp(self): |
| 527 |
self.cli = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDPLITE) |
| 528 |
|
| 529 |
def clientTearDown(self): |
| 530 |
self.cli.close() |
| 531 |
self.cli = None |
| 532 |
ThreadableTest.clientTearDown(self) |
| 533 |
|
| 534 |
class ThreadedCANSocketTest(SocketCANTest, ThreadableTest): |
| 535 |
|
| 536 |
def __init__(self, methodName='runTest'): |
| 537 |
SocketCANTest.__init__(self, methodName=methodName) |
| 538 |
ThreadableTest.__init__(self) |
| 539 |
|
| 540 |
def clientSetUp(self): |
| 541 |
self.cli = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) |
| 542 |
try: |
| 543 |
self.cli.bind((self.interface,)) |
| 544 |
except OSError: |
| 545 |
# skipTest should not be called here, and will be called in the |
| 546 |
# server instead |
| 547 |
pass |
| 548 |
|
| 549 |
def clientTearDown(self): |
| 550 |
self.cli.close() |
| 551 |
self.cli = None |
| 552 |
ThreadableTest.clientTearDown(self) |
| 553 |
|
| 554 |
class ThreadedRDSSocketTest(SocketRDSTest, ThreadableTest): |
| 555 |
|
| 556 |
def __init__(self, methodName='runTest'): |
| 557 |
SocketRDSTest.__init__(self, methodName=methodName) |
| 558 |
ThreadableTest.__init__(self) |
| 559 |
|
| 560 |
def clientSetUp(self): |
| 561 |
self.cli = socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0) |
| 562 |
try: |
| 563 |
# RDS sockets must be bound explicitly to send or receive data |
| 564 |
self.cli.bind((HOST, 0)) |
| 565 |
self.cli_addr = self.cli.getsockname() |
| 566 |
except OSError: |
| 567 |
# skipTest should not be called here, and will be called in the |
| 568 |
# server instead |
| 569 |
pass |
| 570 |
|
| 571 |
def clientTearDown(self): |
| 572 |
self.cli.close() |
| 573 |
self.cli = None |
| 574 |
ThreadableTest.clientTearDown(self) |
| 575 |
|
| 576 |
@unittest.skipIf(fcntl is None, "need fcntl") |
| 577 |
@unittest.skipIf(WSL, 'VSOCK does not work on Microsoft WSL') |
| 578 |
@unittest.skipUnless(HAVE_SOCKET_VSOCK, |
| 579 |
'VSOCK sockets required for this test.') |
| 580 |
@unittest.skipIf(get_cid() == getattr(socket, 'VMADDR_CID_HOST', 2), |
| 581 |
"This test can only be run on a virtual guest.") |
| 582 |
class ThreadedVSOCKSocketStreamTest(unittest.TestCase, ThreadableTest): |
| 583 |
|
| 584 |
def __init__(self, methodName='runTest'): |
| 585 |
unittest.TestCase.__init__(self, methodName=methodName) |
| 586 |
ThreadableTest.__init__(self) |
| 587 |
|
| 588 |
def setUp(self): |
| 589 |
self.serv = socket.socket(socket.AF_VSOCK, socket.SOCK_STREAM) |
| 590 |
self.addCleanup(self.serv.close) |
| 591 |
cid = get_cid() |
| 592 |
if cid in (socket.VMADDR_CID_HOST, socket.VMADDR_CID_ANY): |
| 593 |
cid = socket.VMADDR_CID_LOCAL |
| 594 |
try: |
| 595 |
self.serv.bind((cid, VSOCKPORT)) |
| 596 |
except OSError as exc: |
| 597 |
if exc.errno == errno.EADDRNOTAVAIL: |
| 598 |
self.skipTest(f"bind() failed with {exc!r}") |
| 599 |
else: |
| 600 |
raise |
| 601 |
self.serv.listen() |
| 602 |
self.serverExplicitReady() |
| 603 |
self.serv.settimeout(support.LOOPBACK_TIMEOUT) |
| 604 |
self.conn, self.connaddr = self.serv.accept() |
| 605 |
self.addCleanup(self.conn.close) |
| 606 |
|
| 607 |
def clientSetUp(self): |
| 608 |
time.sleep(0.1) |
| 609 |
self.cli = socket.socket(socket.AF_VSOCK, socket.SOCK_STREAM) |
| 610 |
self.addCleanup(self.cli.close) |
| 611 |
cid = get_cid() |
| 612 |
if cid in (socket.VMADDR_CID_HOST, socket.VMADDR_CID_ANY): |
| 613 |
# gh-119461: Use the local communication address (loopback) |
| 614 |
cid = socket.VMADDR_CID_LOCAL |
| 615 |
self.cli.connect((cid, VSOCKPORT)) |
| 616 |
|
| 617 |
def testStream(self): |
| 618 |
try: |
| 619 |
msg = self.conn.recv(1024) |
| 620 |
except PermissionError as exc: |
| 621 |
self.skipTest(repr(exc)) |
| 622 |
self.assertEqual(msg, MSG) |
| 623 |
|
| 624 |
def _testStream(self): |
| 625 |
self.cli.send(MSG) |
| 626 |
self.cli.close() |
| 627 |
|
| 628 |
class SocketConnectedTest(ThreadedTCPSocketTest): |
| 629 |
"""Socket tests for client-server connection. |
| 630 |
|
| 631 |
self.cli_conn is a client socket connected to the server. The |
| 632 |
setUp() method guarantees that it is connected to the server. |
| 633 |
""" |
| 634 |
|
| 635 |
def __init__(self, methodName='runTest'): |
| 636 |
ThreadedTCPSocketTest.__init__(self, methodName=methodName) |
| 637 |
|
| 638 |
def setUp(self): |
| 639 |
ThreadedTCPSocketTest.setUp(self) |
| 640 |
# Indicate explicitly we're ready for the client thread to |
| 641 |
# proceed and then perform the blocking call to accept |
| 642 |
self.serverExplicitReady() |
| 643 |
conn, addr = self.serv.accept() |
| 644 |
self.cli_conn = conn |
| 645 |
|
| 646 |
def tearDown(self): |
| 647 |
self.cli_conn.close() |
| 648 |
self.cli_conn = None |
| 649 |
ThreadedTCPSocketTest.tearDown(self) |
| 650 |
|
| 651 |
def clientSetUp(self): |
| 652 |
ThreadedTCPSocketTest.clientSetUp(self) |
| 653 |
self.cli.connect((HOST, self.port)) |
| 654 |
self.serv_conn = self.cli |
| 655 |
|
| 656 |
def clientTearDown(self): |
| 657 |
self.serv_conn.close() |
| 658 |
self.serv_conn = None |
| 659 |
ThreadedTCPSocketTest.clientTearDown(self) |
| 660 |
|
| 661 |
class SocketPairTest(unittest.TestCase, ThreadableTest): |
| 662 |
|
| 663 |
def __init__(self, methodName='runTest'): |
| 664 |
unittest.TestCase.__init__(self, methodName=methodName) |
| 665 |
ThreadableTest.__init__(self) |
| 666 |
self.cli = None |
| 667 |
self.serv = None |
| 668 |
|
| 669 |
def socketpair(self): |
| 670 |
# To be overridden by some child classes. |
| 671 |
return socket.socketpair() |
| 672 |
|
| 673 |
def setUp(self): |
| 674 |
self.serv, self.cli = self.socketpair() |
| 675 |
|
| 676 |
def tearDown(self): |
| 677 |
if self.serv: |
| 678 |
self.serv.close() |
| 679 |
self.serv = None |
| 680 |
|
| 681 |
def clientSetUp(self): |
| 682 |
pass |
| 683 |
|
| 684 |
def clientTearDown(self): |
| 685 |
if self.cli: |
| 686 |
self.cli.close() |
| 687 |
self.cli = None |
| 688 |
ThreadableTest.clientTearDown(self) |
| 689 |
|
| 690 |
|
| 691 |
# The following classes are used by the sendmsg()/recvmsg() tests. |
| 692 |
# Combining, for instance, ConnectedStreamTestMixin and TCPTestBase |
| 693 |
# gives a drop-in replacement for SocketConnectedTest, but different |
| 694 |
# address families can be used, and the attributes serv_addr and |
| 695 |
# cli_addr will be set to the addresses of the endpoints. |
| 696 |
|
| 697 |
class SocketTestBase(unittest.TestCase): |
| 698 |
"""A base class for socket tests. |
| 699 |
|
| 700 |
Subclasses must provide methods newSocket() to return a new socket |
| 701 |
and bindSock(sock) to bind it to an unused address. |
| 702 |
|
| 703 |
Creates a socket self.serv and sets self.serv_addr to its address. |
| 704 |
""" |
| 705 |
|
| 706 |
def setUp(self): |
| 707 |
self.serv = self.newSocket() |
| 708 |
self.addCleanup(self.close_server) |
| 709 |
self.bindServer() |
| 710 |
|
| 711 |
def close_server(self): |
| 712 |
self.serv.close() |
| 713 |
self.serv = None |
| 714 |
|
| 715 |
def bindServer(self): |
| 716 |
"""Bind server socket and set self.serv_addr to its address.""" |
| 717 |
self.bindSock(self.serv) |
| 718 |
self.serv_addr = self.serv.getsockname() |
| 719 |
|
| 720 |
|
| 721 |
class SocketListeningTestMixin(SocketTestBase): |
| 722 |
"""Mixin to listen on the server socket.""" |
| 723 |
|
| 724 |
def setUp(self): |
| 725 |
super().setUp() |
| 726 |
self.serv.listen() |
| 727 |
|
| 728 |
|
| 729 |
class ThreadedSocketTestMixin(SocketTestBase, ThreadableTest): |
| 730 |
"""Mixin to add client socket and allow client/server tests. |
| 731 |
|
| 732 |
Client socket is self.cli and its address is self.cli_addr. See |
| 733 |
ThreadableTest for usage information. |
| 734 |
""" |
| 735 |
|
| 736 |
def __init__(self, *args, **kwargs): |
| 737 |
super().__init__(*args, **kwargs) |
| 738 |
ThreadableTest.__init__(self) |
| 739 |
|
| 740 |
def clientSetUp(self): |
| 741 |
self.cli = self.newClientSocket() |
| 742 |
self.bindClient() |
| 743 |
|
| 744 |
def newClientSocket(self): |
| 745 |
"""Return a new socket for use as client.""" |
| 746 |
return self.newSocket() |
| 747 |
|
| 748 |
def bindClient(self): |
| 749 |
"""Bind client socket and set self.cli_addr to its address.""" |
| 750 |
self.bindSock(self.cli) |
| 751 |
self.cli_addr = self.cli.getsockname() |
| 752 |
|
| 753 |
def clientTearDown(self): |
| 754 |
self.cli.close() |
| 755 |
self.cli = None |
| 756 |
ThreadableTest.clientTearDown(self) |
| 757 |
|
| 758 |
|
| 759 |
class ConnectedStreamTestMixin(SocketListeningTestMixin, |
| 760 |
ThreadedSocketTestMixin): |
| 761 |
"""Mixin to allow client/server stream tests with connected client. |
| 762 |
|
| 763 |
Server's socket representing connection to client is self.cli_conn |
| 764 |
and client's connection to server is self.serv_conn. (Based on |
| 765 |
SocketConnectedTest.) |
| 766 |
""" |
| 767 |
|
| 768 |
def setUp(self): |
| 769 |
super().setUp() |
| 770 |
# Indicate explicitly we're ready for the client thread to |
| 771 |
# proceed and then perform the blocking call to accept |
| 772 |
self.serverExplicitReady() |
| 773 |
conn, addr = self.serv.accept() |
| 774 |
self.cli_conn = conn |
| 775 |
|
| 776 |
def tearDown(self): |
| 777 |
self.cli_conn.close() |
| 778 |
self.cli_conn = None |
| 779 |
super().tearDown() |
| 780 |
|
| 781 |
def clientSetUp(self): |
| 782 |
super().clientSetUp() |
| 783 |
self.cli.connect(self.serv_addr) |
| 784 |
self.serv_conn = self.cli |
| 785 |
|
| 786 |
def clientTearDown(self): |
| 787 |
try: |
| 788 |
self.serv_conn.close() |
| 789 |
self.serv_conn = None |
| 790 |
except AttributeError: |
| 791 |
pass |
| 792 |
super().clientTearDown() |
| 793 |
|
| 794 |
|
| 795 |
class UnixSocketTestBase(SocketTestBase): |
| 796 |
"""Base class for Unix-domain socket tests.""" |
| 797 |
|
| 798 |
# This class is used for file descriptor passing tests, so we |
| 799 |
# create the sockets in a private directory so that other users |
| 800 |
# can't send anything that might be problematic for a privileged |
| 801 |
# user running the tests. |
| 802 |
|
| 803 |
def bindSock(self, sock): |
| 804 |
path = socket_helper.create_unix_domain_name() |
| 805 |
self.addCleanup(os_helper.unlink, path) |
| 806 |
socket_helper.bind_unix_socket(sock, path) |
| 807 |
|
| 808 |
class UnixStreamBase(UnixSocketTestBase): |
| 809 |
"""Base class for Unix-domain SOCK_STREAM tests.""" |
| 810 |
|
| 811 |
def newSocket(self): |
| 812 |
return socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
| 813 |
|
| 814 |
|
| 815 |
class InetTestBase(SocketTestBase): |
| 816 |
"""Base class for IPv4 socket tests.""" |
| 817 |
|
| 818 |
host = HOST |
| 819 |
|
| 820 |
def setUp(self): |
| 821 |
super().setUp() |
| 822 |
self.port = self.serv_addr[1] |
| 823 |
|
| 824 |
def bindSock(self, sock): |
| 825 |
socket_helper.bind_port(sock, host=self.host) |
| 826 |
|
| 827 |
class TCPTestBase(InetTestBase): |
| 828 |
"""Base class for TCP-over-IPv4 tests.""" |
| 829 |
|
| 830 |
def newSocket(self): |
| 831 |
return socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 832 |
|
| 833 |
class UDPTestBase(InetTestBase): |
| 834 |
"""Base class for UDP-over-IPv4 tests.""" |
| 835 |
|
| 836 |
def newSocket(self): |
| 837 |
return socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
| 838 |
|
| 839 |
class UDPLITETestBase(InetTestBase): |
| 840 |
"""Base class for UDPLITE-over-IPv4 tests.""" |
| 841 |
|
| 842 |
def newSocket(self): |
| 843 |
return socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDPLITE) |
| 844 |
|
| 845 |
class SCTPStreamBase(InetTestBase): |
| 846 |
"""Base class for SCTP tests in one-to-one (SOCK_STREAM) mode.""" |
| 847 |
|
| 848 |
def newSocket(self): |
| 849 |
return socket.socket(socket.AF_INET, socket.SOCK_STREAM, |
| 850 |
socket.IPPROTO_SCTP) |
| 851 |
|
| 852 |
|
| 853 |
class Inet6TestBase(InetTestBase): |
| 854 |
"""Base class for IPv6 socket tests.""" |
| 855 |
|
| 856 |
host = socket_helper.HOSTv6 |
| 857 |
|
| 858 |
class UDP6TestBase(Inet6TestBase): |
| 859 |
"""Base class for UDP-over-IPv6 tests.""" |
| 860 |
|
| 861 |
def newSocket(self): |
| 862 |
return socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) |
| 863 |
|
| 864 |
class UDPLITE6TestBase(Inet6TestBase): |
| 865 |
"""Base class for UDPLITE-over-IPv6 tests.""" |
| 866 |
|
| 867 |
def newSocket(self): |
| 868 |
return socket.socket(socket.AF_INET6, socket.SOCK_DGRAM, socket.IPPROTO_UDPLITE) |
| 869 |
|
| 870 |
|
| 871 |
# Test-skipping decorators for use with ThreadableTest. |
| 872 |
|
| 873 |
def skipWithClientIf(condition, reason): |
| 874 |
"""Skip decorated test if condition is true, add client_skip decorator. |
| 875 |
|
| 876 |
If the decorated object is not a class, sets its attribute |
| 877 |
"client_skip" to a decorator which will return an empty function |
| 878 |
if the test is to be skipped, or the original function if it is |
| 879 |
not. This can be used to avoid running the client part of a |
| 880 |
skipped test when using ThreadableTest. |
| 881 |
""" |
| 882 |
def client_pass(*args, **kwargs): |
| 883 |
pass |
| 884 |
def skipdec(obj): |
| 885 |
retval = unittest.skip(reason)(obj) |
| 886 |
if not isinstance(obj, type): |
| 887 |
retval.client_skip = lambda f: client_pass |
| 888 |
return retval |
| 889 |
def noskipdec(obj): |
| 890 |
if not (isinstance(obj, type) or hasattr(obj, "client_skip")): |
| 891 |
obj.client_skip = lambda f: f |
| 892 |
return obj |
| 893 |
return skipdec if condition else noskipdec |
| 894 |
|
| 895 |
|
| 896 |
def requireAttrs(obj, *attributes): |
| 897 |
"""Skip decorated test if obj is missing any of the given attributes. |
| 898 |
|
| 899 |
Sets client_skip attribute as skipWithClientIf() does. |
| 900 |
""" |
| 901 |
missing = [name for name in attributes if not hasattr(obj, name)] |
| 902 |
return skipWithClientIf( |
| 903 |
missing, "don't have " + ", ".join(name for name in missing)) |
| 904 |
|
| 905 |
|
| 906 |
def requireSocket(*args): |
| 907 |
"""Skip decorated test if a socket cannot be created with given arguments. |
| 908 |
|
| 909 |
When an argument is given as a string, will use the value of that |
| 910 |
attribute of the socket module, or skip the test if it doesn't |
| 911 |
exist. Sets client_skip attribute as skipWithClientIf() does. |
| 912 |
""" |
| 913 |
err = None |
| 914 |
missing = [obj for obj in args if |
| 915 |
isinstance(obj, str) and not hasattr(socket, obj)] |
| 916 |
if missing: |
| 917 |
err = "don't have " + ", ".join(name for name in missing) |
| 918 |
else: |
| 919 |
callargs = [getattr(socket, obj) if isinstance(obj, str) else obj |
| 920 |
for obj in args] |
| 921 |
try: |
| 922 |
s = socket.socket(*callargs) |
| 923 |
except OSError as e: |
| 924 |
# XXX: check errno? |
| 925 |
err = str(e) |
| 926 |
else: |
| 927 |
s.close() |
| 928 |
return skipWithClientIf( |
| 929 |
err is not None, |
| 930 |
"can't create socket({0}): {1}".format( |
| 931 |
", ".join(str(o) for o in args), err)) |
| 932 |
|
| 933 |
|
| 934 |
####################################################################### |
| 935 |
## Begin Tests |
| 936 |
|
| 937 |
class GeneralModuleTests(unittest.TestCase): |
| 938 |
|
| 939 |
@unittest.skipUnless(_socket is not None, 'need _socket module') |
| 940 |
def test_socket_type(self): |
| 941 |
self.assertTrue(gc.is_tracked(_socket.socket)) |
| 942 |
with self.assertRaisesRegex(TypeError, "immutable"): |
| 943 |
_socket.socket.foo = 1 |
| 944 |
|
| 945 |
def test_SocketType_is_socketobject(self): |
| 946 |
import _socket |
| 947 |
self.assertTrue(socket.SocketType is _socket.socket) |
| 948 |
s = socket.socket() |
| 949 |
self.assertIsInstance(s, socket.SocketType) |
| 950 |
s.close() |
| 951 |
|
| 952 |
def test_repr(self): |
| 953 |
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 954 |
with s: |
| 955 |
self.assertIn('fd=%i' % s.fileno(), repr(s)) |
| 956 |
self.assertIn('family=%s' % socket.AF_INET, repr(s)) |
| 957 |
self.assertIn('type=%s' % socket.SOCK_STREAM, repr(s)) |
| 958 |
self.assertIn('proto=0', repr(s)) |
| 959 |
self.assertNotIn('raddr', repr(s)) |
| 960 |
s.bind(('127.0.0.1', 0)) |
| 961 |
self.assertIn('laddr', repr(s)) |
| 962 |
self.assertIn(str(s.getsockname()), repr(s)) |
| 963 |
self.assertIn('[closed]', repr(s)) |
| 964 |
self.assertNotIn('laddr', repr(s)) |
| 965 |
|
| 966 |
@unittest.skipUnless(_socket is not None, 'need _socket module') |
| 967 |
def test_csocket_repr(self): |
| 968 |
s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM) |
| 969 |
try: |
| 970 |
expected = ('<socket object, fd=%s, family=%s, type=%s, proto=%s>' |
| 971 |
% (s.fileno(), s.family, s.type, s.proto)) |
| 972 |
self.assertEqual(repr(s), expected) |
| 973 |
finally: |
| 974 |
s.close() |
| 975 |
expected = ('<socket object, fd=-1, family=%s, type=%s, proto=%s>' |
| 976 |
% (s.family, s.type, s.proto)) |
| 977 |
self.assertEqual(repr(s), expected) |
| 978 |
|
| 979 |
def test_weakref(self): |
| 980 |
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: |
| 981 |
p = proxy(s) |
| 982 |
self.assertEqual(p.fileno(), s.fileno()) |
| 983 |
s = None |
| 984 |
support.gc_collect() # For PyPy or other GCs. |
| 985 |
try: |
| 986 |
p.fileno() |
| 987 |
except ReferenceError: |
| 988 |
pass |
| 989 |
else: |
| 990 |
self.fail('Socket proxy still exists') |
| 991 |
|
| 992 |
def testSocketError(self): |
| 993 |
# Testing socket module exceptions |
| 994 |
msg = "Error raising socket exception (%s)." |
| 995 |
with self.assertRaises(OSError, msg=msg % 'OSError'): |
| 996 |
raise OSError |
| 997 |
with self.assertRaises(OSError, msg=msg % 'socket.herror'): |
| 998 |
raise socket.herror |
| 999 |
with self.assertRaises(OSError, msg=msg % 'socket.gaierror'): |
| 1000 |
raise socket.gaierror |
| 1001 |
|
| 1002 |
def testSendtoErrors(self): |
| 1003 |
# Testing that sendto doesn't mask failures. See #10169. |
| 1004 |
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
| 1005 |
self.addCleanup(s.close) |
| 1006 |
s.bind(('', 0)) |
| 1007 |
sockname = s.getsockname() |
| 1008 |
# 2 args |
| 1009 |
with self.assertRaises(TypeError) as cm: |
| 1010 |
s.sendto('\u2620', sockname) |
| 1011 |
self.assertEqual(str(cm.exception), |
| 1012 |
"a bytes-like object is required, not 'str'") |
| 1013 |
with self.assertRaises(TypeError) as cm: |
| 1014 |
s.sendto(5j, sockname) |
| 1015 |
self.assertEqual(str(cm.exception), |
| 1016 |
"a bytes-like object is required, not 'complex'") |
| 1017 |
with self.assertRaises(TypeError) as cm: |
| 1018 |
s.sendto(b'foo', None) |
| 1019 |
self.assertIn('not NoneType',str(cm.exception)) |
| 1020 |
# 3 args |
| 1021 |
with self.assertRaises(TypeError) as cm: |
| 1022 |
s.sendto('\u2620', 0, sockname) |
| 1023 |
self.assertEqual(str(cm.exception), |
| 1024 |
"a bytes-like object is required, not 'str'") |
| 1025 |
with self.assertRaises(TypeError) as cm: |
| 1026 |
s.sendto(5j, 0, sockname) |
| 1027 |
self.assertEqual(str(cm.exception), |
| 1028 |
"a bytes-like object is required, not 'complex'") |
| 1029 |
with self.assertRaises(TypeError) as cm: |
| 1030 |
s.sendto(b'foo', 0, None) |
| 1031 |
self.assertIn('not NoneType', str(cm.exception)) |
| 1032 |
with self.assertRaises(TypeError) as cm: |
| 1033 |
s.sendto(b'foo', 'bar', sockname) |
| 1034 |
with self.assertRaises(TypeError) as cm: |
| 1035 |
s.sendto(b'foo', None, None) |
| 1036 |
# wrong number of args |
| 1037 |
with self.assertRaises(TypeError) as cm: |
| 1038 |
s.sendto(b'foo') |
| 1039 |
self.assertIn('(1 given)', str(cm.exception)) |
| 1040 |
with self.assertRaises(TypeError) as cm: |
| 1041 |
s.sendto(b'foo', 0, sockname, 4) |
| 1042 |
self.assertIn('(4 given)', str(cm.exception)) |
| 1043 |
|
| 1044 |
def testCrucialConstants(self): |
| 1045 |
# Testing for mission critical constants |
| 1046 |
socket.AF_INET |
| 1047 |
if socket.has_ipv6: |
| 1048 |
socket.AF_INET6 |
| 1049 |
socket.SOCK_STREAM |
| 1050 |
socket.SOCK_DGRAM |
| 1051 |
socket.SOCK_RAW |
| 1052 |
socket.SOCK_RDM |
| 1053 |
socket.SOCK_SEQPACKET |
| 1054 |
socket.SOL_SOCKET |
| 1055 |
socket.SO_REUSEADDR |
| 1056 |
|
| 1057 |
def testCrucialIpProtoConstants(self): |
| 1058 |
socket.IPPROTO_TCP |
| 1059 |
socket.IPPROTO_UDP |
| 1060 |
if socket.has_ipv6: |
| 1061 |
socket.IPPROTO_IPV6 |
| 1062 |
|
| 1063 |
@unittest.skipUnless(os.name == "nt", "Windows specific") |
| 1064 |
def testWindowsSpecificConstants(self): |
| 1065 |
socket.IPPROTO_ICLFXBM |
| 1066 |
socket.IPPROTO_ST |
| 1067 |
socket.IPPROTO_CBT |
| 1068 |
socket.IPPROTO_IGP |
| 1069 |
socket.IPPROTO_RDP |
| 1070 |
socket.IPPROTO_PGM |
| 1071 |
socket.IPPROTO_L2TP |
| 1072 |
socket.IPPROTO_SCTP |
| 1073 |
|
| 1074 |
@unittest.skipIf(support.is_wasi, "WASI is missing these methods") |
| 1075 |
def test_socket_methods(self): |
| 1076 |
# socket methods that depend on a configure HAVE_ check. They should |
| 1077 |
# be present on all platforms except WASI. |
| 1078 |
names = [ |
| 1079 |
"_accept", "bind", "connect", "connect_ex", "getpeername", |
| 1080 |
"getsockname", "listen", "recvfrom", "recvfrom_into", "sendto", |
| 1081 |
"setsockopt", "shutdown" |
| 1082 |
] |
| 1083 |
for name in names: |
| 1084 |
if not hasattr(socket.socket, name): |
| 1085 |
self.fail(f"socket method {name} is missing") |
| 1086 |
|
| 1087 |
@unittest.skipUnless(sys.platform == 'darwin', 'macOS specific test') |
| 1088 |
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test') |
| 1089 |
def test3542SocketOptions(self): |
| 1090 |
# Ref. issue #35569 and https://tools.ietf.org/html/rfc3542 |
| 1091 |
opts = { |
| 1092 |
'IPV6_CHECKSUM', |
| 1093 |
'IPV6_DONTFRAG', |
| 1094 |
'IPV6_DSTOPTS', |
| 1095 |
'IPV6_HOPLIMIT', |
| 1096 |
'IPV6_HOPOPTS', |
| 1097 |
'IPV6_NEXTHOP', |
| 1098 |
'IPV6_PATHMTU', |
| 1099 |
'IPV6_PKTINFO', |
| 1100 |
'IPV6_RECVDSTOPTS', |
| 1101 |
'IPV6_RECVHOPLIMIT', |
| 1102 |
'IPV6_RECVHOPOPTS', |
| 1103 |
'IPV6_RECVPATHMTU', |
| 1104 |
'IPV6_RECVPKTINFO', |
| 1105 |
'IPV6_RECVRTHDR', |
| 1106 |
'IPV6_RECVTCLASS', |
| 1107 |
'IPV6_RTHDR', |
| 1108 |
'IPV6_RTHDRDSTOPTS', |
| 1109 |
'IPV6_RTHDR_TYPE_0', |
| 1110 |
'IPV6_TCLASS', |
| 1111 |
'IPV6_USE_MIN_MTU', |
| 1112 |
} |
| 1113 |
for opt in opts: |
| 1114 |
self.assertHasAttr(socket, opt) |
| 1115 |
|
| 1116 |
def testHostnameRes(self): |
| 1117 |
# Testing hostname resolution mechanisms |
| 1118 |
hostname = socket.gethostname() |
| 1119 |
try: |
| 1120 |
ip = socket.gethostbyname(hostname) |
| 1121 |
except OSError: |
| 1122 |
# Probably name lookup wasn't set up right; skip this test |
| 1123 |
self.skipTest('name lookup failure') |
| 1124 |
self.assertTrue(ip.find('.') >= 0, "Error resolving host to ip.") |
| 1125 |
try: |
| 1126 |
hname, aliases, ipaddrs = socket.gethostbyaddr(ip) |
| 1127 |
except OSError: |
| 1128 |
# Probably a similar problem as above; skip this test |
| 1129 |
self.skipTest('name lookup failure') |
| 1130 |
all_host_names = [hostname, hname] + aliases |
| 1131 |
fqhn = socket.getfqdn(ip) |
| 1132 |
if not fqhn in all_host_names: |
| 1133 |
self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names))) |
| 1134 |
|
| 1135 |
def test_host_resolution(self): |
| 1136 |
for addr in [socket_helper.HOSTv4, '10.0.0.1', '255.255.255.255']: |
| 1137 |
self.assertEqual(socket.gethostbyname(addr), addr) |
| 1138 |
|
| 1139 |
# we don't test socket_helper.HOSTv6 because there's a chance it doesn't have |
| 1140 |
# a matching name entry (e.g. 'ip6-localhost') |
| 1141 |
for host in [socket_helper.HOSTv4]: |
| 1142 |
self.assertIn(host, socket.gethostbyaddr(host)[2]) |
| 1143 |
|
| 1144 |
def test_host_resolution_bad_address(self): |
| 1145 |
# These are all malformed IP addresses and expected not to resolve to |
| 1146 |
# any result. But some ISPs, e.g. AWS and AT&T, may successfully |
| 1147 |
# resolve these IPs. In particular, AT&T's DNS Error Assist service |
| 1148 |
# will break this test. See https://bugs.python.org/issue42092 for a |
| 1149 |
# workaround. |
| 1150 |
explanation = ( |
| 1151 |
"resolving an invalid IP address did not raise OSError; " |
| 1152 |
"can be caused by a broken DNS server" |
| 1153 |
) |
| 1154 |
for addr in ['0.1.1.~1', '1+.1.1.1', '::1q', '::1::2', |
| 1155 |
'1:1:1:1:1:1:1:1:1']: |
| 1156 |
with self.assertRaises(OSError, msg=addr): |
| 1157 |
socket.gethostbyname(addr) |
| 1158 |
with self.assertRaises(OSError, msg=explanation): |
| 1159 |
socket.gethostbyaddr(addr) |
| 1160 |
|
| 1161 |
@unittest.skipUnless(hasattr(socket, 'sethostname'), "test needs socket.sethostname()") |
| 1162 |
@unittest.skipUnless(hasattr(socket, 'gethostname'), "test needs socket.gethostname()") |
| 1163 |
def test_sethostname(self): |
| 1164 |
oldhn = socket.gethostname() |
| 1165 |
try: |
| 1166 |
socket.sethostname('new') |
| 1167 |
except OSError as e: |
| 1168 |
if e.errno == errno.EPERM: |
| 1169 |
self.skipTest("test should be run as root") |
| 1170 |
else: |
| 1171 |
raise |
| 1172 |
try: |
| 1173 |
# running test as root! |
| 1174 |
self.assertEqual(socket.gethostname(), 'new') |
| 1175 |
# Should work with bytes objects too |
| 1176 |
socket.sethostname(b'bar') |
| 1177 |
self.assertEqual(socket.gethostname(), 'bar') |
| 1178 |
finally: |
| 1179 |
socket.sethostname(oldhn) |
| 1180 |
|
| 1181 |
@unittest.skipUnless(hasattr(socket, 'if_nameindex'), |
| 1182 |
'socket.if_nameindex() not available.') |
| 1183 |
@support.skip_android_selinux('if_nameindex') |
| 1184 |
def testInterfaceNameIndex(self): |
| 1185 |
interfaces = socket.if_nameindex() |
| 1186 |
for index, name in interfaces: |
| 1187 |
self.assertIsInstance(index, int) |
| 1188 |
self.assertIsInstance(name, str) |
| 1189 |
# interface indices are non-zero integers |
| 1190 |
self.assertGreater(index, 0) |
| 1191 |
_index = socket.if_nametoindex(name) |
| 1192 |
self.assertIsInstance(_index, int) |
| 1193 |
self.assertEqual(index, _index) |
| 1194 |
_name = socket.if_indextoname(index) |
| 1195 |
self.assertIsInstance(_name, str) |
| 1196 |
self.assertEqual(name, _name) |
| 1197 |
|
| 1198 |
@unittest.skipUnless(hasattr(socket, 'if_indextoname'), |
| 1199 |
'socket.if_indextoname() not available.') |
| 1200 |
@support.skip_android_selinux('if_indextoname') |
| 1201 |
def testInvalidInterfaceIndexToName(self): |
| 1202 |
with self.assertRaises(OSError) as cm: |
| 1203 |
socket.if_indextoname(0) |
| 1204 |
self.assertIsNotNone(cm.exception.errno) |
| 1205 |
|
| 1206 |
self.assertRaises(ValueError, socket.if_indextoname, -1) |
| 1207 |
self.assertRaises(OverflowError, socket.if_indextoname, 2**1000) |
| 1208 |
self.assertRaises(TypeError, socket.if_indextoname, '_DEADBEEF') |
| 1209 |
if hasattr(socket, 'if_nameindex'): |
| 1210 |
indices = dict(socket.if_nameindex()) |
| 1211 |
for index in indices: |
| 1212 |
index2 = index + 2**32 |
| 1213 |
if index2 not in indices: |
| 1214 |
with self.assertRaises((OverflowError, OSError)): |
| 1215 |
socket.if_indextoname(index2) |
| 1216 |
for index in 2**32-1, 2**64-1: |
| 1217 |
if index not in indices: |
| 1218 |
with self.assertRaises((OverflowError, OSError)): |
| 1219 |
socket.if_indextoname(index) |
| 1220 |
|
| 1221 |
@unittest.skipUnless(hasattr(socket, 'if_nametoindex'), |
| 1222 |
'socket.if_nametoindex() not available.') |
| 1223 |
@support.skip_android_selinux('if_nametoindex') |
| 1224 |
def testInvalidInterfaceNameToIndex(self): |
| 1225 |
with self.assertRaises(OSError) as cm: |
| 1226 |
socket.if_nametoindex("_DEADBEEF") |
| 1227 |
self.assertIsNotNone(cm.exception.errno) |
| 1228 |
|
| 1229 |
self.assertRaises(TypeError, socket.if_nametoindex, 0) |
| 1230 |
|
| 1231 |
@unittest.skipUnless(hasattr(sys, 'getrefcount'), |
| 1232 |
'test needs sys.getrefcount()') |
| 1233 |
def testRefCountGetNameInfo(self): |
| 1234 |
# Testing reference count for getnameinfo |
| 1235 |
try: |
| 1236 |
# On some versions, this loses a reference |
| 1237 |
orig = sys.getrefcount(__name__) |
| 1238 |
socket.getnameinfo(__name__,0) |
| 1239 |
except TypeError: |
| 1240 |
if sys.getrefcount(__name__) != orig: |
| 1241 |
self.fail("socket.getnameinfo loses a reference") |
| 1242 |
|
| 1243 |
def testInterpreterCrash(self): |
| 1244 |
# Making sure getnameinfo doesn't crash the interpreter |
| 1245 |
try: |
| 1246 |
# On some versions, this crashes the interpreter. |
| 1247 |
socket.getnameinfo(('x', 0, 0, 0), 0) |
| 1248 |
except OSError: |
| 1249 |
pass |
| 1250 |
|
| 1251 |
def testNtoH(self): |
| 1252 |
# This just checks that htons etc. are their own inverse, |
| 1253 |
# when looking at the lower 16 or 32 bits. |
| 1254 |
sizes = {socket.htonl: 32, socket.ntohl: 32, |
| 1255 |
socket.htons: 16, socket.ntohs: 16} |
| 1256 |
for func, size in sizes.items(): |
| 1257 |
mask = (1<<size) - 1 |
| 1258 |
for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210): |
| 1259 |
self.assertEqual(i & mask, func(func(i&mask)) & mask) |
| 1260 |
|
| 1261 |
swapped = func(mask) |
| 1262 |
self.assertEqual(swapped & mask, mask) |
| 1263 |
self.assertRaises(OverflowError, func, 1<<34) |
| 1264 |
|
| 1265 |
def testNtoHErrors(self): |
| 1266 |
s_good_values = [0, 1, 2, 0xffff] |
| 1267 |
l_good_values = s_good_values + [0xffffffff] |
| 1268 |
neg_values = [-1, -2, -(1<<15)-1, -(1<<31)-1, -(1<<63)-1, -1<<1000] |
| 1269 |
l_bad_values = [1<<32, 1<<1000] |
| 1270 |
s_bad_values = l_bad_values + [1 << 16, (1<<31)-1, 1<<31] |
| 1271 |
for k in s_good_values: |
| 1272 |
socket.ntohs(k) |
| 1273 |
socket.htons(k) |
| 1274 |
for k in l_good_values: |
| 1275 |
socket.ntohl(k) |
| 1276 |
socket.htonl(k) |
| 1277 |
for k in neg_values: |
| 1278 |
self.assertRaises(ValueError, socket.ntohs, k) |
| 1279 |
self.assertRaises(ValueError, socket.htons, k) |
| 1280 |
self.assertRaises(ValueError, socket.ntohl, k) |
| 1281 |
self.assertRaises(ValueError, socket.htonl, k) |
| 1282 |
for k in s_bad_values: |
| 1283 |
self.assertRaises(OverflowError, socket.ntohs, k) |
| 1284 |
self.assertRaises(OverflowError, socket.htons, k) |
| 1285 |
for k in l_bad_values: |
| 1286 |
self.assertRaises(OverflowError, socket.ntohl, k) |
| 1287 |
self.assertRaises(OverflowError, socket.htonl, k) |
| 1288 |
|
| 1289 |
def testGetServBy(self): |
| 1290 |
eq = self.assertEqual |
| 1291 |
# Find one service that exists, then check all the related interfaces. |
| 1292 |
# I've ordered this by protocols that have both a tcp and udp |
| 1293 |
# protocol, at least for modern Linuxes. |
| 1294 |
if ( |
| 1295 |
sys.platform.startswith( |
| 1296 |
('linux', 'android', 'freebsd', 'netbsd', 'gnukfreebsd')) |
| 1297 |
or is_apple |
| 1298 |
): |
| 1299 |
# avoid the 'echo' service on this platform, as there is an |
| 1300 |
# assumption breaking non-standard port/protocol entry |
| 1301 |
services = ('daytime', 'qotd', 'domain') |
| 1302 |
else: |
| 1303 |
services = ('echo', 'daytime', 'domain') |
| 1304 |
for service in services: |
| 1305 |
try: |
| 1306 |
port = socket.getservbyname(service, 'tcp') |
| 1307 |
break |
| 1308 |
except OSError: |
| 1309 |
pass |
| 1310 |
else: |
| 1311 |
raise OSError |
| 1312 |
# Try same call with optional protocol omitted |
| 1313 |
# Issue gh-71123: this fails on Android before API level 23. |
| 1314 |
if not (support.is_android and platform.android_ver().api_level < 23): |
| 1315 |
port2 = socket.getservbyname(service) |
| 1316 |
eq(port, port2) |
| 1317 |
# Try udp, but don't barf if it doesn't exist |
| 1318 |
try: |
| 1319 |
udpport = socket.getservbyname(service, 'udp') |
| 1320 |
except OSError: |
| 1321 |
udpport = None |
| 1322 |
else: |
| 1323 |
eq(udpport, port) |
| 1324 |
# Now make sure the lookup by port returns the same service name |
| 1325 |
# Issue #26936: when the protocol is omitted, this fails on Android |
| 1326 |
# before API level 28. |
| 1327 |
if not (support.is_android and platform.android_ver().api_level < 28): |
| 1328 |
eq(socket.getservbyport(port2), service) |
| 1329 |
eq(socket.getservbyport(port, 'tcp'), service) |
| 1330 |
if udpport is not None: |
| 1331 |
eq(socket.getservbyport(udpport, 'udp'), service) |
| 1332 |
# Make sure getservbyport does not accept out of range ports. |
| 1333 |
self.assertRaises(OverflowError, socket.getservbyport, -1) |
| 1334 |
self.assertRaises(OverflowError, socket.getservbyport, 65536) |
| 1335 |
|
| 1336 |
def testDefaultTimeout(self): |
| 1337 |
# Testing default timeout |
| 1338 |
# The default timeout should initially be None |
| 1339 |
self.assertEqual(socket.getdefaulttimeout(), None) |
| 1340 |
with socket.socket() as s: |
| 1341 |
self.assertEqual(s.gettimeout(), None) |
| 1342 |
|
| 1343 |
# Set the default timeout to 10, and see if it propagates |
| 1344 |
with socket_setdefaulttimeout(10): |
| 1345 |
self.assertEqual(socket.getdefaulttimeout(), 10) |
| 1346 |
with socket.socket() as sock: |
| 1347 |
self.assertEqual(sock.gettimeout(), 10) |
| 1348 |
|
| 1349 |
# Reset the default timeout to None, and see if it propagates |
| 1350 |
socket.setdefaulttimeout(None) |
| 1351 |
self.assertEqual(socket.getdefaulttimeout(), None) |
| 1352 |
with socket.socket() as sock: |
| 1353 |
self.assertEqual(sock.gettimeout(), None) |
| 1354 |
|
| 1355 |
# Check that setting it to an invalid value raises ValueError |
| 1356 |
self.assertRaises(ValueError, socket.setdefaulttimeout, -1) |
| 1357 |
|
| 1358 |
# Check that setting it to an invalid type raises TypeError |
| 1359 |
self.assertRaises(TypeError, socket.setdefaulttimeout, "spam") |
| 1360 |
|
| 1361 |
@unittest.skipUnless(hasattr(socket, 'inet_aton'), |
| 1362 |
'test needs socket.inet_aton()') |
| 1363 |
def testIPv4_inet_aton_fourbytes(self): |
| 1364 |
# Test that issue1008086 and issue767150 are fixed. |
| 1365 |
# It must return 4 bytes. |
| 1366 |
self.assertEqual(b'\x00'*4, socket.inet_aton('0.0.0.0')) |
| 1367 |
self.assertEqual(b'\xff'*4, socket.inet_aton('255.255.255.255')) |
| 1368 |
|
| 1369 |
@unittest.skipUnless(hasattr(socket, 'inet_pton'), |
| 1370 |
'test needs socket.inet_pton()') |
| 1371 |
def testIPv4toString(self): |
| 1372 |
from socket import inet_aton as f, inet_pton, AF_INET |
| 1373 |
g = lambda a: inet_pton(AF_INET, a) |
| 1374 |
|
| 1375 |
assertInvalid = lambda func,a: self.assertRaises( |
| 1376 |
(OSError, ValueError), func, a |
| 1377 |
) |
| 1378 |
|
| 1379 |
self.assertEqual(b'\x00\x00\x00\x00', f('0.0.0.0')) |
| 1380 |
self.assertEqual(b'\xff\x00\xff\x00', f('255.0.255.0')) |
| 1381 |
self.assertEqual(b'\xaa\xaa\xaa\xaa', f('170.170.170.170')) |
| 1382 |
self.assertEqual(b'\x01\x02\x03\x04', f('1.2.3.4')) |
| 1383 |
self.assertEqual(b'\xff\xff\xff\xff', f('255.255.255.255')) |
| 1384 |
# bpo-29972: inet_pton() doesn't fail on AIX |
| 1385 |
if not AIX: |
| 1386 |
assertInvalid(f, '0.0.0.') |
| 1387 |
assertInvalid(f, '300.0.0.0') |
| 1388 |
assertInvalid(f, 'a.0.0.0') |
| 1389 |
assertInvalid(f, '1.2.3.4.5') |
| 1390 |
assertInvalid(f, '::1') |
| 1391 |
|
| 1392 |
self.assertEqual(b'\x00\x00\x00\x00', g('0.0.0.0')) |
| 1393 |
self.assertEqual(b'\xff\x00\xff\x00', g('255.0.255.0')) |
| 1394 |
self.assertEqual(b'\xaa\xaa\xaa\xaa', g('170.170.170.170')) |
| 1395 |
self.assertEqual(b'\xff\xff\xff\xff', g('255.255.255.255')) |
| 1396 |
assertInvalid(g, '0.0.0.') |
| 1397 |
assertInvalid(g, '300.0.0.0') |
| 1398 |
assertInvalid(g, 'a.0.0.0') |
| 1399 |
assertInvalid(g, '1.2.3.4.5') |
| 1400 |
assertInvalid(g, '::1') |
| 1401 |
|
| 1402 |
@unittest.skipUnless(hasattr(socket, 'inet_pton'), |
| 1403 |
'test needs socket.inet_pton()') |
| 1404 |
def testIPv6toString(self): |
| 1405 |
try: |
| 1406 |
from socket import inet_pton, AF_INET6, has_ipv6 |
| 1407 |
if not has_ipv6: |
| 1408 |
self.skipTest('IPv6 not available') |
| 1409 |
except ImportError: |
| 1410 |
self.skipTest('could not import needed symbols from socket') |
| 1411 |
|
| 1412 |
if sys.platform == "win32": |
| 1413 |
try: |
| 1414 |
inet_pton(AF_INET6, '::') |
| 1415 |
except OSError as e: |
| 1416 |
if e.winerror == 10022: |
| 1417 |
self.skipTest('IPv6 might not be supported') |
| 1418 |
|
| 1419 |
f = lambda a: inet_pton(AF_INET6, a) |
| 1420 |
assertInvalid = lambda a: self.assertRaises( |
| 1421 |
(OSError, ValueError), f, a |
| 1422 |
) |
| 1423 |
|
| 1424 |
self.assertEqual(b'\x00' * 16, f('::')) |
| 1425 |
self.assertEqual(b'\x00' * 16, f('0::0')) |
| 1426 |
self.assertEqual(b'\x00\x01' + b'\x00' * 14, f('1::')) |
| 1427 |
self.assertEqual( |
| 1428 |
b'\x45\xef\x76\xcb\x00\x1a\x56\xef\xaf\xeb\x0b\xac\x19\x24\xae\xae', |
| 1429 |
f('45ef:76cb:1a:56ef:afeb:bac:1924:aeae') |
| 1430 |
) |
| 1431 |
self.assertEqual( |
| 1432 |
b'\xad\x42\x0a\xbc' + b'\x00' * 4 + b'\x01\x27\x00\x00\x02\x54\x00\x02', |
| 1433 |
f('ad42:abc::127:0:254:2') |
| 1434 |
) |
| 1435 |
self.assertEqual(b'\x00\x12\x00\x0a' + b'\x00' * 12, f('12:a::')) |
| 1436 |
assertInvalid('0x20::') |
| 1437 |
assertInvalid(':::') |
| 1438 |
assertInvalid('::0::') |
| 1439 |
assertInvalid('1::abc::') |
| 1440 |
assertInvalid('1::abc::def') |
| 1441 |
assertInvalid('1:2:3:4:5:6') |
| 1442 |
assertInvalid('1:2:3:4:5:6:') |
| 1443 |
assertInvalid('1:2:3:4:5:6:7:8:0') |
| 1444 |
# bpo-29972: inet_pton() doesn't fail on AIX |
| 1445 |
if not AIX: |
| 1446 |
assertInvalid('1:2:3:4:5:6:7:8:') |
| 1447 |
|
| 1448 |
self.assertEqual(b'\x00' * 12 + b'\xfe\x2a\x17\x40', |
| 1449 |
f('::254.42.23.64') |
| 1450 |
) |
| 1451 |
self.assertEqual( |
| 1452 |
b'\x00\x42' + b'\x00' * 8 + b'\xa2\x9b\xfe\x2a\x17\x40', |
| 1453 |
f('42::a29b:254.42.23.64') |
| 1454 |
) |
| 1455 |
self.assertEqual( |
| 1456 |
b'\x00\x42\xa8\xb9\x00\x00\x00\x02\xff\xff\xa2\x9b\xfe\x2a\x17\x40', |
| 1457 |
f('42:a8b9:0:2:ffff:a29b:254.42.23.64') |
| 1458 |
) |
| 1459 |
assertInvalid('255.254.253.252') |
| 1460 |
assertInvalid('1::260.2.3.0') |
| 1461 |
assertInvalid('1::0.be.e.0') |
| 1462 |
assertInvalid('1:2:3:4:5:6:7:1.2.3.4') |
| 1463 |
assertInvalid('::1.2.3.4:0') |
| 1464 |
assertInvalid('0.100.200.0:3:4:5:6:7:8') |
| 1465 |
|
| 1466 |
@unittest.skipUnless(hasattr(socket, 'inet_ntop'), |
| 1467 |
'test needs socket.inet_ntop()') |
| 1468 |
def testStringToIPv4(self): |
| 1469 |
from socket import inet_ntoa as f, inet_ntop, AF_INET |
| 1470 |
g = lambda a: inet_ntop(AF_INET, a) |
| 1471 |
assertInvalid = lambda func,a: self.assertRaises( |
| 1472 |
(OSError, ValueError), func, a |
| 1473 |
) |
| 1474 |
|
| 1475 |
self.assertEqual('1.0.1.0', f(b'\x01\x00\x01\x00')) |
| 1476 |
self.assertEqual('170.85.170.85', f(b'\xaa\x55\xaa\x55')) |
| 1477 |
self.assertEqual('255.255.255.255', f(b'\xff\xff\xff\xff')) |
| 1478 |
self.assertEqual('1.2.3.4', f(b'\x01\x02\x03\x04')) |
| 1479 |
assertInvalid(f, b'\x00' * 3) |
| 1480 |
assertInvalid(f, b'\x00' * 5) |
| 1481 |
assertInvalid(f, b'\x00' * 16) |
| 1482 |
self.assertEqual('170.85.170.85', f(bytearray(b'\xaa\x55\xaa\x55'))) |
| 1483 |
|
| 1484 |
self.assertEqual('1.0.1.0', g(b'\x01\x00\x01\x00')) |
| 1485 |
self.assertEqual('170.85.170.85', g(b'\xaa\x55\xaa\x55')) |
| 1486 |
self.assertEqual('255.255.255.255', g(b'\xff\xff\xff\xff')) |
| 1487 |
assertInvalid(g, b'\x00' * 3) |
| 1488 |
assertInvalid(g, b'\x00' * 5) |
| 1489 |
assertInvalid(g, b'\x00' * 16) |
| 1490 |
self.assertEqual('170.85.170.85', g(bytearray(b'\xaa\x55\xaa\x55'))) |
| 1491 |
|
| 1492 |
@unittest.skipUnless(hasattr(socket, 'inet_ntop'), |
| 1493 |
'test needs socket.inet_ntop()') |
| 1494 |
def testStringToIPv6(self): |
| 1495 |
try: |
| 1496 |
from socket import inet_ntop, AF_INET6, has_ipv6 |
| 1497 |
if not has_ipv6: |
| 1498 |
self.skipTest('IPv6 not available') |
| 1499 |
except ImportError: |
| 1500 |
self.skipTest('could not import needed symbols from socket') |
| 1501 |
|
| 1502 |
if sys.platform == "win32": |
| 1503 |
try: |
| 1504 |
inet_ntop(AF_INET6, b'\x00' * 16) |
| 1505 |
except OSError as e: |
| 1506 |
if e.winerror == 10022: |
| 1507 |
self.skipTest('IPv6 might not be supported') |
| 1508 |
|
| 1509 |
f = lambda a: inet_ntop(AF_INET6, a) |
| 1510 |
assertInvalid = lambda a: self.assertRaises( |
| 1511 |
(OSError, ValueError), f, a |
| 1512 |
) |
| 1513 |
|
| 1514 |
self.assertEqual('::', f(b'\x00' * 16)) |
| 1515 |
self.assertEqual('::1', f(b'\x00' * 15 + b'\x01')) |
| 1516 |
self.assertEqual( |
| 1517 |
'aef:b01:506:1001:ffff:9997:55:170', |
| 1518 |
f(b'\x0a\xef\x0b\x01\x05\x06\x10\x01\xff\xff\x99\x97\x00\x55\x01\x70') |
| 1519 |
) |
| 1520 |
self.assertEqual('::1', f(bytearray(b'\x00' * 15 + b'\x01'))) |
| 1521 |
|
| 1522 |
assertInvalid(b'\x12' * 15) |
| 1523 |
assertInvalid(b'\x12' * 17) |
| 1524 |
assertInvalid(b'\x12' * 4) |
| 1525 |
|
| 1526 |
# XXX The following don't test module-level functionality... |
| 1527 |
|
| 1528 |
def testSockName(self): |
| 1529 |
# Testing getsockname() |
| 1530 |
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 1531 |
self.addCleanup(sock.close) |
| 1532 |
|
| 1533 |
# Since find_unused_port() is inherently subject to race conditions, we |
| 1534 |
# call it a couple times if necessary. |
| 1535 |
for i in itertools.count(): |
| 1536 |
port = socket_helper.find_unused_port() |
| 1537 |
try: |
| 1538 |
sock.bind(("0.0.0.0", port)) |
| 1539 |
except OSError as e: |
| 1540 |
if e.errno != errno.EADDRINUSE or i == 5: |
| 1541 |
raise |
| 1542 |
else: |
| 1543 |
break |
| 1544 |
|
| 1545 |
name = sock.getsockname() |
| 1546 |
# XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate |
| 1547 |
# it reasonable to get the host's addr in addition to 0.0.0.0. |
| 1548 |
# At least for eCos. This is required for the S/390 to pass. |
| 1549 |
try: |
| 1550 |
my_ip_addr = socket.gethostbyname(socket.gethostname()) |
| 1551 |
except OSError: |
| 1552 |
# Probably name lookup wasn't set up right; skip this test |
| 1553 |
self.skipTest('name lookup failure') |
| 1554 |
self.assertIn(name[0], ("0.0.0.0", my_ip_addr), '%s invalid' % name[0]) |
| 1555 |
self.assertEqual(name[1], port) |
| 1556 |
|
| 1557 |
def testGetSockOpt(self): |
| 1558 |
# Testing getsockopt() |
| 1559 |
# We know a socket should start without reuse==0 |
| 1560 |
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 1561 |
self.addCleanup(sock.close) |
| 1562 |
reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) |
| 1563 |
self.assertFalse(reuse != 0, "initial mode is reuse") |
| 1564 |
|
| 1565 |
def testSetSockOpt(self): |
| 1566 |
# Testing setsockopt() |
| 1567 |
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 1568 |
self.addCleanup(sock.close) |
| 1569 |
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 1570 |
reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) |
| 1571 |
self.assertFalse(reuse == 0, "failed to set reuse mode") |
| 1572 |
|
| 1573 |
def testSendAfterClose(self): |
| 1574 |
# testing send() after close() with timeout |
| 1575 |
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: |
| 1576 |
sock.settimeout(1) |
| 1577 |
self.assertRaises(OSError, sock.send, b"spam") |
| 1578 |
|
| 1579 |
def testCloseException(self): |
| 1580 |
sock = socket.socket() |
| 1581 |
sock.bind((socket._LOCALHOST, 0)) |
| 1582 |
socket.socket(fileno=sock.fileno()).close() |
| 1583 |
try: |
| 1584 |
sock.close() |
| 1585 |
except OSError as err: |
| 1586 |
# Winsock apparently raises ENOTSOCK |
| 1587 |
self.assertIn(err.errno, (errno.EBADF, errno.ENOTSOCK)) |
| 1588 |
else: |
| 1589 |
self.fail("close() should raise EBADF/ENOTSOCK") |
| 1590 |
|
| 1591 |
def testNewAttributes(self): |
| 1592 |
# testing .family, .type and .protocol |
| 1593 |
|
| 1594 |
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: |
| 1595 |
self.assertEqual(sock.family, socket.AF_INET) |
| 1596 |
if hasattr(socket, 'SOCK_CLOEXEC'): |
| 1597 |
self.assertIn(sock.type, |
| 1598 |
(socket.SOCK_STREAM | socket.SOCK_CLOEXEC, |
| 1599 |
socket.SOCK_STREAM)) |
| 1600 |
else: |
| 1601 |
self.assertEqual(sock.type, socket.SOCK_STREAM) |
| 1602 |
self.assertEqual(sock.proto, 0) |
| 1603 |
|
| 1604 |
def test_getsockaddrarg(self): |
| 1605 |
sock = socket.socket() |
| 1606 |
self.addCleanup(sock.close) |
| 1607 |
port = socket_helper.find_unused_port() |
| 1608 |
big_port = port + 65536 |
| 1609 |
neg_port = port - 65536 |
| 1610 |
self.assertRaises(OverflowError, sock.bind, (HOST, big_port)) |
| 1611 |
self.assertRaises(OverflowError, sock.bind, (HOST, neg_port)) |
| 1612 |
# Since find_unused_port() is inherently subject to race conditions, we |
| 1613 |
# call it a couple times if necessary. |
| 1614 |
for i in itertools.count(): |
| 1615 |
port = socket_helper.find_unused_port() |
| 1616 |
try: |
| 1617 |
sock.bind((HOST, port)) |
| 1618 |
except OSError as e: |
| 1619 |
if e.errno != errno.EADDRINUSE or i == 5: |
| 1620 |
raise |
| 1621 |
else: |
| 1622 |
break |
| 1623 |
|
| 1624 |
@unittest.skipUnless(os.name == "nt", "Windows specific") |
| 1625 |
def test_sock_ioctl(self): |
| 1626 |
self.assertHasAttr(socket.socket, 'ioctl') |
| 1627 |
self.assertHasAttr(socket, 'SIO_RCVALL') |
| 1628 |
self.assertHasAttr(socket, 'RCVALL_ON') |
| 1629 |
self.assertHasAttr(socket, 'RCVALL_OFF') |
| 1630 |
self.assertHasAttr(socket, 'SIO_KEEPALIVE_VALS') |
| 1631 |
s = socket.socket() |
| 1632 |
self.addCleanup(s.close) |
| 1633 |
self.assertRaises(ValueError, s.ioctl, -1, None) |
| 1634 |
s.ioctl(socket.SIO_KEEPALIVE_VALS, (1, 100, 100)) |
| 1635 |
|
| 1636 |
@unittest.skipUnless(os.name == "nt", "Windows specific") |
| 1637 |
@unittest.skipUnless(hasattr(socket, 'SIO_LOOPBACK_FAST_PATH'), |
| 1638 |
'Loopback fast path support required for this test') |
| 1639 |
def test_sio_loopback_fast_path(self): |
| 1640 |
s = socket.socket() |
| 1641 |
self.addCleanup(s.close) |
| 1642 |
try: |
| 1643 |
s.ioctl(socket.SIO_LOOPBACK_FAST_PATH, True) |
| 1644 |
except OSError as exc: |
| 1645 |
WSAEOPNOTSUPP = 10045 |
| 1646 |
if exc.winerror == WSAEOPNOTSUPP: |
| 1647 |
self.skipTest("SIO_LOOPBACK_FAST_PATH is defined but " |
| 1648 |
"doesn't implemented in this Windows version") |
| 1649 |
raise |
| 1650 |
self.assertRaises(TypeError, s.ioctl, socket.SIO_LOOPBACK_FAST_PATH, None) |
| 1651 |
|
| 1652 |
def testGetaddrinfo(self): |
| 1653 |
try: |
| 1654 |
socket.getaddrinfo('localhost', 80) |
| 1655 |
except socket.gaierror as err: |
| 1656 |
if err.errno == socket.EAI_SERVICE: |
| 1657 |
# see http://bugs.python.org/issue1282647 |
| 1658 |
self.skipTest("buggy libc version") |
| 1659 |
raise |
| 1660 |
# len of every sequence is supposed to be == 5 |
| 1661 |
for info in socket.getaddrinfo(HOST, None): |
| 1662 |
self.assertEqual(len(info), 5) |
| 1663 |
# host can be a domain name, a string representation of an |
| 1664 |
# IPv4/v6 address or None |
| 1665 |
socket.getaddrinfo('localhost', 80) |
| 1666 |
socket.getaddrinfo('127.0.0.1', 80) |
| 1667 |
socket.getaddrinfo(None, 80) |
| 1668 |
if socket_helper.IPV6_ENABLED: |
| 1669 |
socket.getaddrinfo('::1', 80) |
| 1670 |
# port can be a string service name such as "http", a numeric |
| 1671 |
# port number or None |
| 1672 |
# Issue #26936: this fails on Android before API level 23. |
| 1673 |
if not (support.is_android and platform.android_ver().api_level < 23): |
| 1674 |
socket.getaddrinfo(HOST, "http") |
| 1675 |
socket.getaddrinfo(HOST, 80) |
| 1676 |
socket.getaddrinfo(HOST, None) |
| 1677 |
# test family and socktype filters |
| 1678 |
infos = socket.getaddrinfo(HOST, 80, socket.AF_INET, socket.SOCK_STREAM) |
| 1679 |
for family, type, _, _, _ in infos: |
| 1680 |
self.assertEqual(family, socket.AF_INET) |
| 1681 |
self.assertEqual(repr(family), '<AddressFamily.AF_INET: %r>' % family.value) |
| 1682 |
self.assertEqual(str(family), str(family.value)) |
| 1683 |
self.assertEqual(type, socket.SOCK_STREAM) |
| 1684 |
self.assertEqual(repr(type), '<SocketKind.SOCK_STREAM: %r>' % type.value) |
| 1685 |
self.assertEqual(str(type), str(type.value)) |
| 1686 |
infos = socket.getaddrinfo(HOST, None, 0, socket.SOCK_STREAM) |
| 1687 |
for _, socktype, _, _, _ in infos: |
| 1688 |
self.assertEqual(socktype, socket.SOCK_STREAM) |
| 1689 |
# test proto and flags arguments |
| 1690 |
socket.getaddrinfo(HOST, None, 0, 0, socket.SOL_TCP) |
| 1691 |
socket.getaddrinfo(HOST, None, 0, 0, 0, socket.AI_PASSIVE) |
| 1692 |
# a server willing to support both IPv4 and IPv6 will |
| 1693 |
# usually do this |
| 1694 |
socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, |
| 1695 |
socket.AI_PASSIVE) |
| 1696 |
# test keyword arguments |
| 1697 |
a = socket.getaddrinfo(HOST, None) |
| 1698 |
b = socket.getaddrinfo(host=HOST, port=None) |
| 1699 |
self.assertEqual(a, b) |
| 1700 |
a = socket.getaddrinfo(HOST, None, socket.AF_INET) |
| 1701 |
b = socket.getaddrinfo(HOST, None, family=socket.AF_INET) |
| 1702 |
self.assertEqual(a, b) |
| 1703 |
a = socket.getaddrinfo(HOST, None, 0, socket.SOCK_STREAM) |
| 1704 |
b = socket.getaddrinfo(HOST, None, type=socket.SOCK_STREAM) |
| 1705 |
self.assertEqual(a, b) |
| 1706 |
a = socket.getaddrinfo(HOST, None, 0, 0, socket.SOL_TCP) |
| 1707 |
b = socket.getaddrinfo(HOST, None, proto=socket.SOL_TCP) |
| 1708 |
self.assertEqual(a, b) |
| 1709 |
a = socket.getaddrinfo(HOST, None, 0, 0, 0, socket.AI_PASSIVE) |
| 1710 |
b = socket.getaddrinfo(HOST, None, flags=socket.AI_PASSIVE) |
| 1711 |
self.assertEqual(a, b) |
| 1712 |
a = socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, |
| 1713 |
socket.AI_PASSIVE) |
| 1714 |
b = socket.getaddrinfo(host=None, port=0, family=socket.AF_UNSPEC, |
| 1715 |
type=socket.SOCK_STREAM, proto=0, |
| 1716 |
flags=socket.AI_PASSIVE) |
| 1717 |
self.assertEqual(a, b) |
| 1718 |
# Issue #6697. |
| 1719 |
self.assertRaises(UnicodeEncodeError, socket.getaddrinfo, 'localhost', '\uD800') |
| 1720 |
|
| 1721 |
if hasattr(socket, 'AI_NUMERICSERV'): |
| 1722 |
self.assertRaises(socket.gaierror, socket.getaddrinfo, "localhost", "http", |
| 1723 |
flags=socket.AI_NUMERICSERV) |
| 1724 |
|
| 1725 |
# Issue 17269: test workaround for OS X platform bug segfault |
| 1726 |
try: |
| 1727 |
# The arguments here are undefined and the call may succeed |
| 1728 |
# or fail. All we care here is that it doesn't segfault. |
| 1729 |
socket.getaddrinfo("localhost", None, 0, 0, 0, |
| 1730 |
socket.AI_NUMERICSERV) |
| 1731 |
except socket.gaierror: |
| 1732 |
pass |
| 1733 |
|
| 1734 |
@unittest.skipIf(_testcapi is None, "requires _testcapi") |
| 1735 |
def test_getaddrinfo_int_port_overflow(self): |
| 1736 |
# gh-74895: Test that getaddrinfo does not raise OverflowError on port. |
| 1737 |
# |
| 1738 |
# POSIX getaddrinfo() never specify the valid range for "service" |
| 1739 |
# decimal port number values. For IPv4 and IPv6 they are technically |
| 1740 |
# unsigned 16-bit values, but the API is protocol agnostic. Which values |
| 1741 |
# trigger an error from the C library function varies by platform as |
| 1742 |
# they do not all perform validation. |
| 1743 |
|
| 1744 |
# The key here is that we don't want to produce OverflowError as Python |
| 1745 |
# prior to 3.12 did for ints outside of a [LONG_MIN, LONG_MAX] range. |
| 1746 |
# Leave the error up to the underlying string based platform C API. |
| 1747 |
|
| 1748 |
from _testcapi import ULONG_MAX, LONG_MAX, LONG_MIN |
| 1749 |
try: |
| 1750 |
socket.getaddrinfo(None, ULONG_MAX + 1, type=socket.SOCK_STREAM) |
| 1751 |
except OverflowError: |
| 1752 |
# Platforms differ as to what values constitute a getaddrinfo() error |
| 1753 |
# return. Some fail for LONG_MAX+1, others ULONG_MAX+1, and Windows |
| 1754 |
# silently accepts such huge "port" aka "service" numeric values. |
| 1755 |
self.fail("Either no error or socket.gaierror expected.") |
| 1756 |
except socket.gaierror: |
| 1757 |
pass |
| 1758 |
|
| 1759 |
try: |
| 1760 |
socket.getaddrinfo(None, LONG_MAX + 1, type=socket.SOCK_STREAM) |
| 1761 |
except OverflowError: |
| 1762 |
self.fail("Either no error or socket.gaierror expected.") |
| 1763 |
except socket.gaierror: |
| 1764 |
pass |
| 1765 |
|
| 1766 |
try: |
| 1767 |
socket.getaddrinfo(None, LONG_MAX - 0xffff + 1, type=socket.SOCK_STREAM) |
| 1768 |
except OverflowError: |
| 1769 |
self.fail("Either no error or socket.gaierror expected.") |
| 1770 |
except socket.gaierror: |
| 1771 |
pass |
| 1772 |
|
| 1773 |
try: |
| 1774 |
socket.getaddrinfo(None, LONG_MIN - 1, type=socket.SOCK_STREAM) |
| 1775 |
except OverflowError: |
| 1776 |
self.fail("Either no error or socket.gaierror expected.") |
| 1777 |
except socket.gaierror: |
| 1778 |
pass |
| 1779 |
|
| 1780 |
socket.getaddrinfo(None, 0, type=socket.SOCK_STREAM) # No error expected. |
| 1781 |
socket.getaddrinfo(None, 0xffff, type=socket.SOCK_STREAM) # No error expected. |
| 1782 |
|
| 1783 |
def test_getnameinfo(self): |
| 1784 |
# only IP addresses are allowed |
| 1785 |
self.assertRaises(OSError, socket.getnameinfo, ('mail.python.org',0), 0) |
| 1786 |
|
| 1787 |
@unittest.skipUnless(support.is_resource_enabled('network'), |
| 1788 |
'network is not enabled') |
| 1789 |
def test_idna(self): |
| 1790 |
# Check for internet access before running test |
| 1791 |
# (issue #12804, issue #25138). |
| 1792 |
with socket_helper.transient_internet('python.org'): |
| 1793 |
socket.gethostbyname('python.org') |
| 1794 |
|
| 1795 |
# these should all be successful |
| 1796 |
domain = 'испытание.pythontest.net' |
| 1797 |
socket.gethostbyname(domain) |
| 1798 |
socket.gethostbyname_ex(domain) |
| 1799 |
socket.getaddrinfo(domain,0,socket.AF_UNSPEC,socket.SOCK_STREAM) |
| 1800 |
# this may not work if the forward lookup chooses the IPv6 address, as that doesn't |
| 1801 |
# have a reverse entry yet |
| 1802 |
# socket.gethostbyaddr('испытание.python.org') |
| 1803 |
|
| 1804 |
def check_sendall_interrupted(self, with_timeout): |
| 1805 |
# socketpair() is not strictly required, but it makes things easier. |
| 1806 |
if not hasattr(signal, 'alarm') or not hasattr(socket, 'socketpair'): |
| 1807 |
self.skipTest("signal.alarm and socket.socketpair required for this test") |
| 1808 |
# Our signal handlers clobber the C errno by calling a math function |
| 1809 |
# with an invalid domain value. |
| 1810 |
def ok_handler(*args): |
| 1811 |
self.assertRaises(ValueError, math.acosh, 0) |
| 1812 |
def raising_handler(*args): |
| 1813 |
self.assertRaises(ValueError, math.acosh, 0) |
| 1814 |
1 // 0 |
| 1815 |
c, s = socket.socketpair() |
| 1816 |
old_alarm = signal.signal(signal.SIGALRM, raising_handler) |
| 1817 |
try: |
| 1818 |
if with_timeout: |
| 1819 |
# Just above the one second minimum for signal.alarm |
| 1820 |
c.settimeout(1.5) |
| 1821 |
with self.assertRaises(ZeroDivisionError): |
| 1822 |
signal.alarm(1) |
| 1823 |
c.sendall(b"x" * support.SOCK_MAX_SIZE) |
| 1824 |
if with_timeout: |
| 1825 |
signal.signal(signal.SIGALRM, ok_handler) |
| 1826 |
signal.alarm(1) |
| 1827 |
self.assertRaises(TimeoutError, c.sendall, |
| 1828 |
b"x" * support.SOCK_MAX_SIZE) |
| 1829 |
finally: |
| 1830 |
signal.alarm(0) |
| 1831 |
signal.signal(signal.SIGALRM, old_alarm) |
| 1832 |
c.close() |
| 1833 |
s.close() |
| 1834 |
|
| 1835 |
def test_sendall_interrupted(self): |
| 1836 |
self.check_sendall_interrupted(False) |
| 1837 |
|
| 1838 |
def test_sendall_interrupted_with_timeout(self): |
| 1839 |
self.check_sendall_interrupted(True) |
| 1840 |
|
| 1841 |
def test_dealloc_warn(self): |
| 1842 |
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 1843 |
r = repr(sock) |
| 1844 |
with self.assertWarns(ResourceWarning) as cm: |
| 1845 |
sock = None |
| 1846 |
support.gc_collect() |
| 1847 |
self.assertIn(r, str(cm.warning.args[0])) |
| 1848 |
# An open socket file object gets dereferenced after the socket |
| 1849 |
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 1850 |
f = sock.makefile('rb') |
| 1851 |
r = repr(sock) |
| 1852 |
sock = None |
| 1853 |
support.gc_collect() |
| 1854 |
with self.assertWarns(ResourceWarning): |
| 1855 |
f = None |
| 1856 |
support.gc_collect() |
| 1857 |
|
| 1858 |
def test_name_closed_socketio(self): |
| 1859 |
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: |
| 1860 |
fp = sock.makefile("rb") |
| 1861 |
fp.close() |
| 1862 |
self.assertEqual(repr(fp), "<_io.BufferedReader name=-1>") |
| 1863 |
|
| 1864 |
def test_unusable_closed_socketio(self): |
| 1865 |
with socket.socket() as sock: |
| 1866 |
fp = sock.makefile("rb", buffering=0) |
| 1867 |
self.assertTrue(fp.readable()) |
| 1868 |
self.assertFalse(fp.writable()) |
| 1869 |
self.assertFalse(fp.seekable()) |
| 1870 |
fp.close() |
| 1871 |
self.assertRaises(ValueError, fp.readable) |
| 1872 |
self.assertRaises(ValueError, fp.writable) |
| 1873 |
self.assertRaises(ValueError, fp.seekable) |
| 1874 |
|
| 1875 |
def test_socket_close(self): |
| 1876 |
sock = socket.socket() |
| 1877 |
try: |
| 1878 |
sock.bind((HOST, 0)) |
| 1879 |
socket.close(sock.fileno()) |
| 1880 |
with self.assertRaises(OSError): |
| 1881 |
sock.listen(1) |
| 1882 |
finally: |
| 1883 |
with self.assertRaises(OSError): |
| 1884 |
# sock.close() fails with EBADF |
| 1885 |
sock.close() |
| 1886 |
with self.assertRaises(TypeError): |
| 1887 |
socket.close(None) |
| 1888 |
with self.assertRaises(OSError): |
| 1889 |
socket.close(-1) |
| 1890 |
|
| 1891 |
def test_makefile_mode(self): |
| 1892 |
for mode in 'r', 'rb', 'rw', 'w', 'wb': |
| 1893 |
with self.subTest(mode=mode): |
| 1894 |
with socket.socket() as sock: |
| 1895 |
encoding = None if "b" in mode else "utf-8" |
| 1896 |
with sock.makefile(mode, encoding=encoding) as fp: |
| 1897 |
self.assertEqual(fp.mode, mode) |
| 1898 |
|
| 1899 |
def test_makefile_invalid_mode(self): |
| 1900 |
for mode in 'rt', 'x', '+', 'a': |
| 1901 |
with self.subTest(mode=mode): |
| 1902 |
with socket.socket() as sock: |
| 1903 |
with self.assertRaisesRegex(ValueError, 'invalid mode'): |
| 1904 |
sock.makefile(mode) |
| 1905 |
|
| 1906 |
def test_pickle(self): |
| 1907 |
sock = socket.socket() |
| 1908 |
with sock: |
| 1909 |
for protocol in range(pickle.HIGHEST_PROTOCOL + 1): |
| 1910 |
self.assertRaises(TypeError, pickle.dumps, sock, protocol) |
| 1911 |
for protocol in range(pickle.HIGHEST_PROTOCOL + 1): |
| 1912 |
family = pickle.loads(pickle.dumps(socket.AF_INET, protocol)) |
| 1913 |
self.assertEqual(family, socket.AF_INET) |
| 1914 |
type = pickle.loads(pickle.dumps(socket.SOCK_STREAM, protocol)) |
| 1915 |
self.assertEqual(type, socket.SOCK_STREAM) |
| 1916 |
|
| 1917 |
def test_listen_backlog(self): |
| 1918 |
for backlog in 0, -1: |
| 1919 |
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as srv: |
| 1920 |
srv.bind((HOST, 0)) |
| 1921 |
srv.listen(backlog) |
| 1922 |
|
| 1923 |
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as srv: |
| 1924 |
srv.bind((HOST, 0)) |
| 1925 |
srv.listen() |
| 1926 |
|
| 1927 |
@support.cpython_only |
| 1928 |
@unittest.skipIf(_testcapi is None, "requires _testcapi") |
| 1929 |
def test_listen_backlog_overflow(self): |
| 1930 |
# Issue 15989 |
| 1931 |
import _testcapi |
| 1932 |
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as srv: |
| 1933 |
srv.bind((HOST, 0)) |
| 1934 |
self.assertRaises(OverflowError, srv.listen, _testcapi.INT_MAX + 1) |
| 1935 |
|
| 1936 |
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.') |
| 1937 |
def test_flowinfo(self): |
| 1938 |
self.assertRaises(OverflowError, socket.getnameinfo, |
| 1939 |
(socket_helper.HOSTv6, 0, 0xffffffff), 0) |
| 1940 |
with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s: |
| 1941 |
self.assertRaises(OverflowError, s.bind, (socket_helper.HOSTv6, 0, -10)) |
| 1942 |
|
| 1943 |
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.') |
| 1944 |
def test_getaddrinfo_ipv6_basic(self): |
| 1945 |
((*_, sockaddr),) = socket.getaddrinfo( |
| 1946 |
'ff02::1de:c0:face:8D', # Note capital letter `D`. |
| 1947 |
1234, socket.AF_INET6, |
| 1948 |
socket.SOCK_DGRAM, |
| 1949 |
socket.IPPROTO_UDP |
| 1950 |
) |
| 1951 |
self.assertEqual(sockaddr, ('ff02::1de:c0:face:8d', 1234, 0, 0)) |
| 1952 |
|
| 1953 |
def test_getfqdn_filter_localhost(self): |
| 1954 |
self.assertEqual(socket.getfqdn(), socket.getfqdn("0.0.0.0")) |
| 1955 |
self.assertEqual(socket.getfqdn(), socket.getfqdn("::")) |
| 1956 |
|
| 1957 |
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.') |
| 1958 |
@unittest.skipIf(sys.platform == 'win32', 'does not work on Windows') |
| 1959 |
@unittest.skipIf(AIX, 'Symbolic scope id does not work') |
| 1960 |
@unittest.skipUnless(hasattr(socket, 'if_nameindex'), "test needs socket.if_nameindex()") |
| 1961 |
@support.skip_android_selinux('if_nameindex') |
| 1962 |
def test_getaddrinfo_ipv6_scopeid_symbolic(self): |
| 1963 |
# Just pick up any network interface (Linux, Mac OS X) |
| 1964 |
(ifindex, test_interface) = socket.if_nameindex()[0] |
| 1965 |
((*_, sockaddr),) = socket.getaddrinfo( |
| 1966 |
'ff02::1de:c0:face:8D%' + test_interface, |
| 1967 |
1234, socket.AF_INET6, |
| 1968 |
socket.SOCK_DGRAM, |
| 1969 |
socket.IPPROTO_UDP |
| 1970 |
) |
| 1971 |
# Note missing interface name part in IPv6 address |
| 1972 |
self.assertEqual(sockaddr, ('ff02::1de:c0:face:8d', 1234, 0, ifindex)) |
| 1973 |
|
| 1974 |
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.') |
| 1975 |
@unittest.skipUnless( |
| 1976 |
sys.platform == 'win32', |
| 1977 |
'Numeric scope id does not work or undocumented') |
| 1978 |
def test_getaddrinfo_ipv6_scopeid_numeric(self): |
| 1979 |
# Also works on Linux and Mac OS X, but is not documented (?) |
| 1980 |
# Windows, Linux and Max OS X allow nonexistent interface numbers here. |
| 1981 |
ifindex = 42 |
| 1982 |
((*_, sockaddr),) = socket.getaddrinfo( |
| 1983 |
'ff02::1de:c0:face:8D%' + str(ifindex), |
| 1984 |
1234, socket.AF_INET6, |
| 1985 |
socket.SOCK_DGRAM, |
| 1986 |
socket.IPPROTO_UDP |
| 1987 |
) |
| 1988 |
# Note missing interface name part in IPv6 address |
| 1989 |
self.assertEqual(sockaddr, ('ff02::1de:c0:face:8d', 1234, 0, ifindex)) |
| 1990 |
|
| 1991 |
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.') |
| 1992 |
@unittest.skipIf(sys.platform == 'win32', 'does not work on Windows') |
| 1993 |
@unittest.skipIf(AIX, 'Symbolic scope id does not work') |
| 1994 |
@unittest.skipUnless(hasattr(socket, 'if_nameindex'), "test needs socket.if_nameindex()") |
| 1995 |
@support.skip_android_selinux('if_nameindex') |
| 1996 |
def test_getnameinfo_ipv6_scopeid_symbolic(self): |
| 1997 |
# Just pick up any network interface. |
| 1998 |
(ifindex, test_interface) = socket.if_nameindex()[0] |
| 1999 |
sockaddr = ('ff02::1de:c0:face:8D', 1234, 0, ifindex) # Note capital letter `D`. |
| 2000 |
nameinfo = socket.getnameinfo(sockaddr, socket.NI_NUMERICHOST | socket.NI_NUMERICSERV) |
| 2001 |
self.assertEqual(nameinfo, ('ff02::1de:c0:face:8d%' + test_interface, '1234')) |
| 2002 |
|
| 2003 |
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.') |
| 2004 |
@unittest.skipUnless( sys.platform == 'win32', |
| 2005 |
'Numeric scope id does not work or undocumented') |
| 2006 |
def test_getnameinfo_ipv6_scopeid_numeric(self): |
| 2007 |
# Also works on Linux (undocumented), but does not work on Mac OS X |
| 2008 |
# Windows and Linux allow nonexistent interface numbers here. |
| 2009 |
ifindex = 42 |
| 2010 |
sockaddr = ('ff02::1de:c0:face:8D', 1234, 0, ifindex) # Note capital letter `D`. |
| 2011 |
nameinfo = socket.getnameinfo(sockaddr, socket.NI_NUMERICHOST | socket.NI_NUMERICSERV) |
| 2012 |
self.assertEqual(nameinfo, ('ff02::1de:c0:face:8d%' + str(ifindex), '1234')) |
| 2013 |
|
| 2014 |
def test_str_for_enums(self): |
| 2015 |
# Make sure that the AF_* and SOCK_* constants have enum-like string |
| 2016 |
# reprs. |
| 2017 |
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: |
| 2018 |
self.assertEqual(repr(s.family), '<AddressFamily.AF_INET: %r>' % s.family.value) |
| 2019 |
self.assertEqual(repr(s.type), '<SocketKind.SOCK_STREAM: %r>' % s.type.value) |
| 2020 |
self.assertEqual(str(s.family), str(s.family.value)) |
| 2021 |
self.assertEqual(str(s.type), str(s.type.value)) |
| 2022 |
|
| 2023 |
def test_socket_consistent_sock_type(self): |
| 2024 |
SOCK_NONBLOCK = getattr(socket, 'SOCK_NONBLOCK', 0) |
| 2025 |
SOCK_CLOEXEC = getattr(socket, 'SOCK_CLOEXEC', 0) |
| 2026 |
sock_type = socket.SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC |
| 2027 |
|
| 2028 |
with socket.socket(socket.AF_INET, sock_type) as s: |
| 2029 |
self.assertEqual(s.type, socket.SOCK_STREAM) |
| 2030 |
s.settimeout(1) |
| 2031 |
self.assertEqual(s.type, socket.SOCK_STREAM) |
| 2032 |
s.settimeout(0) |
| 2033 |
self.assertEqual(s.type, socket.SOCK_STREAM) |
| 2034 |
s.setblocking(True) |
| 2035 |
self.assertEqual(s.type, socket.SOCK_STREAM) |
| 2036 |
s.setblocking(False) |
| 2037 |
self.assertEqual(s.type, socket.SOCK_STREAM) |
| 2038 |
|
| 2039 |
def test_unknown_socket_family_repr(self): |
| 2040 |
# Test that when created with a family that's not one of the known |
| 2041 |
# AF_*/SOCK_* constants, socket.family just returns the number. |
| 2042 |
# |
| 2043 |
# To do this we fool socket.socket into believing it already has an |
| 2044 |
# open fd because on this path it doesn't actually verify the family and |
| 2045 |
# type and populates the socket object. |
| 2046 |
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 2047 |
fd = sock.detach() |
| 2048 |
unknown_family = max(socket.AddressFamily.__members__.values()) + 1 |
| 2049 |
|
| 2050 |
unknown_type = max( |
| 2051 |
kind |
| 2052 |
for name, kind in socket.SocketKind.__members__.items() |
| 2053 |
if name not in {'SOCK_NONBLOCK', 'SOCK_CLOEXEC'} |
| 2054 |
) + 1 |
| 2055 |
|
| 2056 |
with socket.socket( |
| 2057 |
family=unknown_family, type=unknown_type, proto=23, |
| 2058 |
fileno=fd) as s: |
| 2059 |
self.assertEqual(s.family, unknown_family) |
| 2060 |
self.assertEqual(s.type, unknown_type) |
| 2061 |
# some OS like macOS ignore proto |
| 2062 |
self.assertIn(s.proto, {0, 23}) |
| 2063 |
|
| 2064 |
@unittest.skipUnless(hasattr(os, 'sendfile'), 'test needs os.sendfile()') |
| 2065 |
def test__sendfile_use_sendfile(self): |
| 2066 |
class File: |
| 2067 |
def __init__(self, fd): |
| 2068 |
self.fd = fd |
| 2069 |
|
| 2070 |
def fileno(self): |
| 2071 |
return self.fd |
| 2072 |
with socket.socket() as sock: |
| 2073 |
fd = os.open(os.curdir, os.O_RDONLY) |
| 2074 |
os.close(fd) |
| 2075 |
with self.assertRaises(socket._GiveupOnSendfile): |
| 2076 |
sock._sendfile_use_sendfile(File(fd)) |
| 2077 |
with self.assertRaises(OverflowError): |
| 2078 |
sock._sendfile_use_sendfile(File(2**1000)) |
| 2079 |
with self.assertRaises(TypeError): |
| 2080 |
sock._sendfile_use_sendfile(File(None)) |
| 2081 |
|
| 2082 |
def _test_socket_fileno(self, s, family, stype): |
| 2083 |
self.assertEqual(s.family, family) |
| 2084 |
self.assertEqual(s.type, stype) |
| 2085 |
|
| 2086 |
fd = s.fileno() |
| 2087 |
s2 = socket.socket(fileno=fd) |
| 2088 |
self.addCleanup(s2.close) |
| 2089 |
# detach old fd to avoid double close |
| 2090 |
s.detach() |
| 2091 |
self.assertEqual(s2.family, family) |
| 2092 |
self.assertEqual(s2.type, stype) |
| 2093 |
self.assertEqual(s2.fileno(), fd) |
| 2094 |
|
| 2095 |
def test_socket_fileno(self): |
| 2096 |
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 2097 |
self.addCleanup(s.close) |
| 2098 |
s.bind((socket_helper.HOST, 0)) |
| 2099 |
self._test_socket_fileno(s, socket.AF_INET, socket.SOCK_STREAM) |
| 2100 |
|
| 2101 |
if hasattr(socket, "SOCK_DGRAM"): |
| 2102 |
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
| 2103 |
self.addCleanup(s.close) |
| 2104 |
s.bind((socket_helper.HOST, 0)) |
| 2105 |
self._test_socket_fileno(s, socket.AF_INET, socket.SOCK_DGRAM) |
| 2106 |
|
| 2107 |
if socket_helper.IPV6_ENABLED: |
| 2108 |
s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) |
| 2109 |
self.addCleanup(s.close) |
| 2110 |
s.bind((socket_helper.HOSTv6, 0, 0, 0)) |
| 2111 |
self._test_socket_fileno(s, socket.AF_INET6, socket.SOCK_STREAM) |
| 2112 |
|
| 2113 |
if hasattr(socket, "AF_UNIX"): |
| 2114 |
unix_name = socket_helper.create_unix_domain_name() |
| 2115 |
self.addCleanup(os_helper.unlink, unix_name) |
| 2116 |
|
| 2117 |
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
| 2118 |
with s: |
| 2119 |
try: |
| 2120 |
s.bind(unix_name) |
| 2121 |
except PermissionError: |
| 2122 |
pass |
| 2123 |
else: |
| 2124 |
self._test_socket_fileno(s, socket.AF_UNIX, |
| 2125 |
socket.SOCK_STREAM) |
| 2126 |
|
| 2127 |
def test_socket_fileno_rejects_float(self): |
| 2128 |
with self.assertRaises(TypeError): |
| 2129 |
socket.socket(socket.AF_INET, socket.SOCK_STREAM, fileno=42.5) |
| 2130 |
|
| 2131 |
def test_socket_fileno_rejects_other_types(self): |
| 2132 |
with self.assertRaises(TypeError): |
| 2133 |
socket.socket(socket.AF_INET, socket.SOCK_STREAM, fileno="foo") |
| 2134 |
|
| 2135 |
def test_socket_fileno_rejects_invalid_socket(self): |
| 2136 |
with self.assertRaisesRegex(ValueError, "negative file descriptor"): |
| 2137 |
socket.socket(socket.AF_INET, socket.SOCK_STREAM, fileno=-1) |
| 2138 |
|
| 2139 |
@unittest.skipIf(os.name == "nt", "Windows disallows -1 only") |
| 2140 |
def test_socket_fileno_rejects_negative(self): |
| 2141 |
with self.assertRaisesRegex(ValueError, "negative file descriptor"): |
| 2142 |
socket.socket(socket.AF_INET, socket.SOCK_STREAM, fileno=-42) |
| 2143 |
|
| 2144 |
def test_socket_fileno_requires_valid_fd(self): |
| 2145 |
WSAENOTSOCK = 10038 |
| 2146 |
with self.assertRaises(OSError) as cm: |
| 2147 |
socket.socket(fileno=os_helper.make_bad_fd()) |
| 2148 |
self.assertIn(cm.exception.errno, (errno.EBADF, WSAENOTSOCK)) |
| 2149 |
|
| 2150 |
with self.assertRaises(OSError) as cm: |
| 2151 |
socket.socket( |
| 2152 |
socket.AF_INET, |
| 2153 |
socket.SOCK_STREAM, |
| 2154 |
fileno=os_helper.make_bad_fd()) |
| 2155 |
self.assertIn(cm.exception.errno, (errno.EBADF, WSAENOTSOCK)) |
| 2156 |
|
| 2157 |
def test_socket_fileno_requires_socket_fd(self): |
| 2158 |
with tempfile.NamedTemporaryFile() as afile: |
| 2159 |
with self.assertRaises(OSError): |
| 2160 |
socket.socket(fileno=afile.fileno()) |
| 2161 |
|
| 2162 |
with self.assertRaises(OSError) as cm: |
| 2163 |
socket.socket( |
| 2164 |
socket.AF_INET, |
| 2165 |
socket.SOCK_STREAM, |
| 2166 |
fileno=afile.fileno()) |
| 2167 |
self.assertEqual(cm.exception.errno, errno.ENOTSOCK) |
| 2168 |
|
| 2169 |
def test_addressfamily_enum(self): |
| 2170 |
import _socket, enum |
| 2171 |
CheckedAddressFamily = enum._old_convert_( |
| 2172 |
enum.IntEnum, 'AddressFamily', 'socket', |
| 2173 |
lambda C: C.isupper() and C.startswith('AF_'), |
| 2174 |
source=_socket, |
| 2175 |
) |
| 2176 |
enum._test_simple_enum(CheckedAddressFamily, socket.AddressFamily) |
| 2177 |
|
| 2178 |
def test_socketkind_enum(self): |
| 2179 |
import _socket, enum |
| 2180 |
CheckedSocketKind = enum._old_convert_( |
| 2181 |
enum.IntEnum, 'SocketKind', 'socket', |
| 2182 |
lambda C: C.isupper() and C.startswith('SOCK_'), |
| 2183 |
source=_socket, |
| 2184 |
) |
| 2185 |
enum._test_simple_enum(CheckedSocketKind, socket.SocketKind) |
| 2186 |
|
| 2187 |
def test_msgflag_enum(self): |
| 2188 |
import _socket, enum |
| 2189 |
CheckedMsgFlag = enum._old_convert_( |
| 2190 |
enum.IntFlag, 'MsgFlag', 'socket', |
| 2191 |
lambda C: C.isupper() and C.startswith('MSG_'), |
| 2192 |
source=_socket, |
| 2193 |
) |
| 2194 |
enum._test_simple_enum(CheckedMsgFlag, socket.MsgFlag) |
| 2195 |
|
| 2196 |
def test_addressinfo_enum(self): |
| 2197 |
import _socket, enum |
| 2198 |
CheckedAddressInfo = enum._old_convert_( |
| 2199 |
enum.IntFlag, 'AddressInfo', 'socket', |
| 2200 |
lambda C: C.isupper() and C.startswith('AI_'), |
| 2201 |
source=_socket) |
| 2202 |
enum._test_simple_enum(CheckedAddressInfo, socket.AddressInfo) |
| 2203 |
|
| 2204 |
@unittest.skipUnless(hasattr(socket.socket, "sendmsg"),"sendmsg not supported") |
| 2205 |
def test_sendmsg_reentrant_ancillary_mutation(self): |
| 2206 |
|
| 2207 |
class Mut: |
| 2208 |
def __index__(self): |
| 2209 |
seq.clear() |
| 2210 |
return socket.SCM_RIGHTS |
| 2211 |
|
| 2212 |
seq = [ |
| 2213 |
(socket.SOL_SOCKET, Mut(), b'xxxx'), |
| 2214 |
(socket.SOL_SOCKET, socket.SCM_RIGHTS, b'xxxx'), |
| 2215 |
] |
| 2216 |
|
| 2217 |
left, right = socket.socketpair() |
| 2218 |
self.addCleanup(left.close) |
| 2219 |
self.addCleanup(right.close) |
| 2220 |
self.assertRaises(OSError, left.sendmsg, [b'x'], seq) |
| 2221 |
|
| 2222 |
|
| 2223 |
@unittest.skipUnless(HAVE_SOCKET_CAN, 'SocketCan required for this test.') |
| 2224 |
class BasicCANTest(unittest.TestCase): |
| 2225 |
|
| 2226 |
def testCrucialConstants(self): |
| 2227 |
socket.AF_CAN |
| 2228 |
socket.PF_CAN |
| 2229 |
socket.CAN_RAW |
| 2230 |
|
| 2231 |
@unittest.skipUnless(hasattr(socket, "CAN_BCM"), |
| 2232 |
'socket.CAN_BCM required for this test.') |
| 2233 |
def testBCMConstants(self): |
| 2234 |
socket.CAN_BCM |
| 2235 |
|
| 2236 |
# opcodes |
| 2237 |
socket.CAN_BCM_TX_SETUP # create (cyclic) transmission task |
| 2238 |
socket.CAN_BCM_TX_DELETE # remove (cyclic) transmission task |
| 2239 |
socket.CAN_BCM_TX_READ # read properties of (cyclic) transmission task |
| 2240 |
socket.CAN_BCM_TX_SEND # send one CAN frame |
| 2241 |
socket.CAN_BCM_RX_SETUP # create RX content filter subscription |
| 2242 |
socket.CAN_BCM_RX_DELETE # remove RX content filter subscription |
| 2243 |
socket.CAN_BCM_RX_READ # read properties of RX content filter subscription |
| 2244 |
socket.CAN_BCM_TX_STATUS # reply to TX_READ request |
| 2245 |
socket.CAN_BCM_TX_EXPIRED # notification on performed transmissions (count=0) |
| 2246 |
socket.CAN_BCM_RX_STATUS # reply to RX_READ request |
| 2247 |
socket.CAN_BCM_RX_TIMEOUT # cyclic message is absent |
| 2248 |
socket.CAN_BCM_RX_CHANGED # updated CAN frame (detected content change) |
| 2249 |
|
| 2250 |
# flags |
| 2251 |
socket.CAN_BCM_SETTIMER |
| 2252 |
socket.CAN_BCM_STARTTIMER |
| 2253 |
socket.CAN_BCM_TX_COUNTEVT |
| 2254 |
socket.CAN_BCM_TX_ANNOUNCE |
| 2255 |
socket.CAN_BCM_TX_CP_CAN_ID |
| 2256 |
socket.CAN_BCM_RX_FILTER_ID |
| 2257 |
socket.CAN_BCM_RX_CHECK_DLC |
| 2258 |
socket.CAN_BCM_RX_NO_AUTOTIMER |
| 2259 |
socket.CAN_BCM_RX_ANNOUNCE_RESUME |
| 2260 |
socket.CAN_BCM_TX_RESET_MULTI_IDX |
| 2261 |
socket.CAN_BCM_RX_RTR_FRAME |
| 2262 |
|
| 2263 |
def testCreateSocket(self): |
| 2264 |
with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s: |
| 2265 |
pass |
| 2266 |
|
| 2267 |
@unittest.skipUnless(hasattr(socket, "CAN_BCM"), |
| 2268 |
'socket.CAN_BCM required for this test.') |
| 2269 |
def testCreateBCMSocket(self): |
| 2270 |
with socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_BCM) as s: |
| 2271 |
pass |
| 2272 |
|
| 2273 |
def testBindAny(self): |
| 2274 |
with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s: |
| 2275 |
address = ('', ) |
| 2276 |
s.bind(address) |
| 2277 |
self.assertEqual(s.getsockname(), address) |
| 2278 |
|
| 2279 |
def testTooLongInterfaceName(self): |
| 2280 |
# most systems limit IFNAMSIZ to 16, take 1024 to be sure |
| 2281 |
with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s: |
| 2282 |
self.assertRaisesRegex(OSError, 'interface name too long', |
| 2283 |
s.bind, ('x' * 1024,)) |
| 2284 |
|
| 2285 |
@unittest.skipUnless(hasattr(socket, "CAN_RAW_LOOPBACK"), |
| 2286 |
'socket.CAN_RAW_LOOPBACK required for this test.') |
| 2287 |
def testLoopback(self): |
| 2288 |
with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s: |
| 2289 |
for loopback in (0, 1): |
| 2290 |
s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_LOOPBACK, |
| 2291 |
loopback) |
| 2292 |
self.assertEqual(loopback, |
| 2293 |
s.getsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_LOOPBACK)) |
| 2294 |
|
| 2295 |
@unittest.skipUnless(hasattr(socket, "CAN_RAW_FILTER"), |
| 2296 |
'socket.CAN_RAW_FILTER required for this test.') |
| 2297 |
def testFilter(self): |
| 2298 |
can_id, can_mask = 0x200, 0x700 |
| 2299 |
can_filter = struct.pack("=II", can_id, can_mask) |
| 2300 |
with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s: |
| 2301 |
s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FILTER, can_filter) |
| 2302 |
self.assertEqual(can_filter, |
| 2303 |
s.getsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FILTER, 8)) |
| 2304 |
s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FILTER, bytearray(can_filter)) |
| 2305 |
|
| 2306 |
|
| 2307 |
@unittest.skipUnless(HAVE_SOCKET_CAN, 'SocketCan required for this test.') |
| 2308 |
class CANTest(ThreadedCANSocketTest): |
| 2309 |
|
| 2310 |
def __init__(self, methodName='runTest'): |
| 2311 |
ThreadedCANSocketTest.__init__(self, methodName=methodName) |
| 2312 |
|
| 2313 |
@classmethod |
| 2314 |
def build_can_frame(cls, can_id, data): |
| 2315 |
"""Build a CAN frame.""" |
| 2316 |
can_dlc = len(data) |
| 2317 |
data = data.ljust(8, b'\x00') |
| 2318 |
return struct.pack(cls.can_frame_fmt, can_id, can_dlc, data) |
| 2319 |
|
| 2320 |
@classmethod |
| 2321 |
def dissect_can_frame(cls, frame): |
| 2322 |
"""Dissect a CAN frame.""" |
| 2323 |
can_id, can_dlc, data = struct.unpack(cls.can_frame_fmt, frame) |
| 2324 |
return (can_id, can_dlc, data[:can_dlc]) |
| 2325 |
|
| 2326 |
def testSendFrame(self): |
| 2327 |
cf, addr = self.s.recvfrom(self.bufsize) |
| 2328 |
self.assertEqual(self.cf, cf) |
| 2329 |
self.assertEqual(addr[0], self.interface) |
| 2330 |
|
| 2331 |
def _testSendFrame(self): |
| 2332 |
self.cf = self.build_can_frame(0x00, b'\x01\x02\x03\x04\x05') |
| 2333 |
self.cli.send(self.cf) |
| 2334 |
|
| 2335 |
def testSendMaxFrame(self): |
| 2336 |
cf, addr = self.s.recvfrom(self.bufsize) |
| 2337 |
self.assertEqual(self.cf, cf) |
| 2338 |
|
| 2339 |
def _testSendMaxFrame(self): |
| 2340 |
self.cf = self.build_can_frame(0x00, b'\x07' * 8) |
| 2341 |
self.cli.send(self.cf) |
| 2342 |
|
| 2343 |
def testSendMultiFrames(self): |
| 2344 |
cf, addr = self.s.recvfrom(self.bufsize) |
| 2345 |
self.assertEqual(self.cf1, cf) |
| 2346 |
|
| 2347 |
cf, addr = self.s.recvfrom(self.bufsize) |
| 2348 |
self.assertEqual(self.cf2, cf) |
| 2349 |
|
| 2350 |
def _testSendMultiFrames(self): |
| 2351 |
self.cf1 = self.build_can_frame(0x07, b'\x44\x33\x22\x11') |
| 2352 |
self.cli.send(self.cf1) |
| 2353 |
|
| 2354 |
self.cf2 = self.build_can_frame(0x12, b'\x99\x22\x33') |
| 2355 |
self.cli.send(self.cf2) |
| 2356 |
|
| 2357 |
@unittest.skipUnless(hasattr(socket, "CAN_BCM"), |
| 2358 |
'socket.CAN_BCM required for this test.') |
| 2359 |
def _testBCM(self): |
| 2360 |
cf, addr = self.cli.recvfrom(self.bufsize) |
| 2361 |
self.assertEqual(self.cf, cf) |
| 2362 |
can_id, can_dlc, data = self.dissect_can_frame(cf) |
| 2363 |
self.assertEqual(self.can_id, can_id) |
| 2364 |
self.assertEqual(self.data, data) |
| 2365 |
|
| 2366 |
@unittest.skipUnless(hasattr(socket, "CAN_BCM"), |
| 2367 |
'socket.CAN_BCM required for this test.') |
| 2368 |
def testBCM(self): |
| 2369 |
bcm = socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_BCM) |
| 2370 |
self.addCleanup(bcm.close) |
| 2371 |
bcm.connect((self.interface,)) |
| 2372 |
self.can_id = 0x123 |
| 2373 |
self.data = bytes([0xc0, 0xff, 0xee]) |
| 2374 |
self.cf = self.build_can_frame(self.can_id, self.data) |
| 2375 |
opcode = socket.CAN_BCM_TX_SEND |
| 2376 |
flags = 0 |
| 2377 |
count = 0 |
| 2378 |
ival1_seconds = ival1_usec = ival2_seconds = ival2_usec = 0 |
| 2379 |
bcm_can_id = 0x0222 |
| 2380 |
nframes = 1 |
| 2381 |
assert len(self.cf) == 16 |
| 2382 |
header = struct.pack(self.bcm_cmd_msg_fmt, |
| 2383 |
opcode, |
| 2384 |
flags, |
| 2385 |
count, |
| 2386 |
ival1_seconds, |
| 2387 |
ival1_usec, |
| 2388 |
ival2_seconds, |
| 2389 |
ival2_usec, |
| 2390 |
bcm_can_id, |
| 2391 |
nframes, |
| 2392 |
) |
| 2393 |
header_plus_frame = header + self.cf |
| 2394 |
bytes_sent = bcm.send(header_plus_frame) |
| 2395 |
self.assertEqual(bytes_sent, len(header_plus_frame)) |
| 2396 |
|
| 2397 |
|
| 2398 |
@unittest.skipUnless(HAVE_SOCKET_CAN_ISOTP, 'CAN ISOTP required for this test.') |
| 2399 |
class ISOTPTest(unittest.TestCase): |
| 2400 |
|
| 2401 |
def __init__(self, *args, **kwargs): |
| 2402 |
super().__init__(*args, **kwargs) |
| 2403 |
self.interface = "vcan0" |
| 2404 |
|
| 2405 |
def testCrucialConstants(self): |
| 2406 |
socket.AF_CAN |
| 2407 |
socket.PF_CAN |
| 2408 |
socket.CAN_ISOTP |
| 2409 |
socket.SOCK_DGRAM |
| 2410 |
|
| 2411 |
def testCreateSocket(self): |
| 2412 |
with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s: |
| 2413 |
pass |
| 2414 |
|
| 2415 |
@unittest.skipUnless(hasattr(socket, "CAN_ISOTP"), |
| 2416 |
'socket.CAN_ISOTP required for this test.') |
| 2417 |
def testCreateISOTPSocket(self): |
| 2418 |
with socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_ISOTP) as s: |
| 2419 |
pass |
| 2420 |
|
| 2421 |
def testTooLongInterfaceName(self): |
| 2422 |
# most systems limit IFNAMSIZ to 16, take 1024 to be sure |
| 2423 |
with socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_ISOTP) as s: |
| 2424 |
with self.assertRaisesRegex(OSError, 'interface name too long'): |
| 2425 |
s.bind(('x' * 1024, 1, 2)) |
| 2426 |
|
| 2427 |
def testBind(self): |
| 2428 |
try: |
| 2429 |
with socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_ISOTP) as s: |
| 2430 |
addr = self.interface, 0x123, 0x456 |
| 2431 |
s.bind(addr) |
| 2432 |
self.assertEqual(s.getsockname(), addr) |
| 2433 |
except OSError as e: |
| 2434 |
if e.errno == errno.ENODEV: |
| 2435 |
self.skipTest('network interface `%s` does not exist' % |
| 2436 |
self.interface) |
| 2437 |
else: |
| 2438 |
raise |
| 2439 |
|
| 2440 |
|
| 2441 |
@unittest.skipUnless(HAVE_SOCKET_CAN_J1939, 'CAN J1939 required for this test.') |
| 2442 |
class J1939Test(unittest.TestCase): |
| 2443 |
|
| 2444 |
def __init__(self, *args, **kwargs): |
| 2445 |
super().__init__(*args, **kwargs) |
| 2446 |
self.interface = "vcan0" |
| 2447 |
|
| 2448 |
@unittest.skipUnless(hasattr(socket, "CAN_J1939"), |
| 2449 |
'socket.CAN_J1939 required for this test.') |
| 2450 |
def testJ1939Constants(self): |
| 2451 |
socket.CAN_J1939 |
| 2452 |
|
| 2453 |
socket.J1939_MAX_UNICAST_ADDR |
| 2454 |
socket.J1939_IDLE_ADDR |
| 2455 |
socket.J1939_NO_ADDR |
| 2456 |
socket.J1939_NO_NAME |
| 2457 |
socket.J1939_PGN_REQUEST |
| 2458 |
socket.J1939_PGN_ADDRESS_CLAIMED |
| 2459 |
socket.J1939_PGN_ADDRESS_COMMANDED |
| 2460 |
socket.J1939_PGN_PDU1_MAX |
| 2461 |
socket.J1939_PGN_MAX |
| 2462 |
socket.J1939_NO_PGN |
| 2463 |
|
| 2464 |
# J1939 socket options |
| 2465 |
socket.SO_J1939_FILTER |
| 2466 |
socket.SO_J1939_PROMISC |
| 2467 |
socket.SO_J1939_SEND_PRIO |
| 2468 |
socket.SO_J1939_ERRQUEUE |
| 2469 |
|
| 2470 |
socket.SCM_J1939_DEST_ADDR |
| 2471 |
socket.SCM_J1939_DEST_NAME |
| 2472 |
socket.SCM_J1939_PRIO |
| 2473 |
socket.SCM_J1939_ERRQUEUE |
| 2474 |
|
| 2475 |
socket.J1939_NLA_PAD |
| 2476 |
socket.J1939_NLA_BYTES_ACKED |
| 2477 |
|
| 2478 |
socket.J1939_EE_INFO_NONE |
| 2479 |
socket.J1939_EE_INFO_TX_ABORT |
| 2480 |
|
| 2481 |
socket.J1939_FILTER_MAX |
| 2482 |
|
| 2483 |
@unittest.skipUnless(hasattr(socket, "CAN_J1939"), |
| 2484 |
'socket.CAN_J1939 required for this test.') |
| 2485 |
def testCreateJ1939Socket(self): |
| 2486 |
with socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_J1939) as s: |
| 2487 |
pass |
| 2488 |
|
| 2489 |
def testBind(self): |
| 2490 |
try: |
| 2491 |
with socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_J1939) as s: |
| 2492 |
addr = self.interface, socket.J1939_NO_NAME, socket.J1939_NO_PGN, socket.J1939_NO_ADDR |
| 2493 |
s.bind(addr) |
| 2494 |
self.assertEqual(s.getsockname(), addr) |
| 2495 |
except OSError as e: |
| 2496 |
if e.errno == errno.ENODEV: |
| 2497 |
self.skipTest('network interface `%s` does not exist' % |
| 2498 |
self.interface) |
| 2499 |
else: |
| 2500 |
raise |
| 2501 |
|
| 2502 |
|
| 2503 |
@unittest.skipUnless(HAVE_SOCKET_RDS, 'RDS sockets required for this test.') |
| 2504 |
class BasicRDSTest(unittest.TestCase): |
| 2505 |
|
| 2506 |
def testCrucialConstants(self): |
| 2507 |
socket.AF_RDS |
| 2508 |
socket.PF_RDS |
| 2509 |
|
| 2510 |
def testCreateSocket(self): |
| 2511 |
with socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0) as s: |
| 2512 |
pass |
| 2513 |
|
| 2514 |
def testSocketBufferSize(self): |
| 2515 |
bufsize = 16384 |
| 2516 |
with socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0) as s: |
| 2517 |
s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, bufsize) |
| 2518 |
s.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, bufsize) |
| 2519 |
|
| 2520 |
|
| 2521 |
@unittest.skipUnless(HAVE_SOCKET_RDS, 'RDS sockets required for this test.') |
| 2522 |
class RDSTest(ThreadedRDSSocketTest): |
| 2523 |
|
| 2524 |
def __init__(self, methodName='runTest'): |
| 2525 |
ThreadedRDSSocketTest.__init__(self, methodName=methodName) |
| 2526 |
|
| 2527 |
def setUp(self): |
| 2528 |
super().setUp() |
| 2529 |
self.evt = threading.Event() |
| 2530 |
|
| 2531 |
def testSendAndRecv(self): |
| 2532 |
data, addr = self.serv.recvfrom(self.bufsize) |
| 2533 |
self.assertEqual(self.data, data) |
| 2534 |
self.assertEqual(self.cli_addr, addr) |
| 2535 |
|
| 2536 |
def _testSendAndRecv(self): |
| 2537 |
self.data = b'spam' |
| 2538 |
self.cli.sendto(self.data, 0, (HOST, self.port)) |
| 2539 |
|
| 2540 |
def testPeek(self): |
| 2541 |
data, addr = self.serv.recvfrom(self.bufsize, socket.MSG_PEEK) |
| 2542 |
self.assertEqual(self.data, data) |
| 2543 |
data, addr = self.serv.recvfrom(self.bufsize) |
| 2544 |
self.assertEqual(self.data, data) |
| 2545 |
|
| 2546 |
def _testPeek(self): |
| 2547 |
self.data = b'spam' |
| 2548 |
self.cli.sendto(self.data, 0, (HOST, self.port)) |
| 2549 |
|
| 2550 |
@requireAttrs(socket.socket, 'recvmsg') |
| 2551 |
def testSendAndRecvMsg(self): |
| 2552 |
data, ancdata, msg_flags, addr = self.serv.recvmsg(self.bufsize) |
| 2553 |
self.assertEqual(self.data, data) |
| 2554 |
|
| 2555 |
@requireAttrs(socket.socket, 'sendmsg') |
| 2556 |
def _testSendAndRecvMsg(self): |
| 2557 |
self.data = b'hello ' * 10 |
| 2558 |
self.cli.sendmsg([self.data], (), 0, (HOST, self.port)) |
| 2559 |
|
| 2560 |
def testSendAndRecvMulti(self): |
| 2561 |
data, addr = self.serv.recvfrom(self.bufsize) |
| 2562 |
self.assertEqual(self.data1, data) |
| 2563 |
|
| 2564 |
data, addr = self.serv.recvfrom(self.bufsize) |
| 2565 |
self.assertEqual(self.data2, data) |
| 2566 |
|
| 2567 |
def _testSendAndRecvMulti(self): |
| 2568 |
self.data1 = b'bacon' |
| 2569 |
self.cli.sendto(self.data1, 0, (HOST, self.port)) |
| 2570 |
|
| 2571 |
self.data2 = b'egg' |
| 2572 |
self.cli.sendto(self.data2, 0, (HOST, self.port)) |
| 2573 |
|
| 2574 |
def testSelect(self): |
| 2575 |
r, w, x = select.select([self.serv], [], [], 3.0) |
| 2576 |
self.assertIn(self.serv, r) |
| 2577 |
data, addr = self.serv.recvfrom(self.bufsize) |
| 2578 |
self.assertEqual(self.data, data) |
| 2579 |
|
| 2580 |
def _testSelect(self): |
| 2581 |
self.data = b'select' |
| 2582 |
self.cli.sendto(self.data, 0, (HOST, self.port)) |
| 2583 |
|
| 2584 |
@unittest.skipUnless(HAVE_SOCKET_QIPCRTR, |
| 2585 |
'QIPCRTR sockets required for this test.') |
| 2586 |
class BasicQIPCRTRTest(unittest.TestCase): |
| 2587 |
|
| 2588 |
def testCrucialConstants(self): |
| 2589 |
socket.AF_QIPCRTR |
| 2590 |
|
| 2591 |
def testCreateSocket(self): |
| 2592 |
with socket.socket(socket.AF_QIPCRTR, socket.SOCK_DGRAM) as s: |
| 2593 |
pass |
| 2594 |
|
| 2595 |
def testUnbound(self): |
| 2596 |
with socket.socket(socket.AF_QIPCRTR, socket.SOCK_DGRAM) as s: |
| 2597 |
self.assertEqual(s.getsockname()[1], 0) |
| 2598 |
|
| 2599 |
def testBindSock(self): |
| 2600 |
with socket.socket(socket.AF_QIPCRTR, socket.SOCK_DGRAM) as s: |
| 2601 |
socket_helper.bind_port(s, host=s.getsockname()[0]) |
| 2602 |
self.assertNotEqual(s.getsockname()[1], 0) |
| 2603 |
|
| 2604 |
def testInvalidBindSock(self): |
| 2605 |
with socket.socket(socket.AF_QIPCRTR, socket.SOCK_DGRAM) as s: |
| 2606 |
self.assertRaises(OSError, socket_helper.bind_port, s, host=-2) |
| 2607 |
|
| 2608 |
def testAutoBindSock(self): |
| 2609 |
with socket.socket(socket.AF_QIPCRTR, socket.SOCK_DGRAM) as s: |
| 2610 |
s.connect((123, 123)) |
| 2611 |
self.assertNotEqual(s.getsockname()[1], 0) |
| 2612 |
|
| 2613 |
@unittest.skipIf(fcntl is None, "need fcntl") |
| 2614 |
@unittest.skipUnless(HAVE_SOCKET_VSOCK, |
| 2615 |
'VSOCK sockets required for this test.') |
| 2616 |
class BasicVSOCKTest(unittest.TestCase): |
| 2617 |
|
| 2618 |
def testCrucialConstants(self): |
| 2619 |
socket.AF_VSOCK |
| 2620 |
|
| 2621 |
def testVSOCKConstants(self): |
| 2622 |
socket.SO_VM_SOCKETS_BUFFER_SIZE |
| 2623 |
socket.SO_VM_SOCKETS_BUFFER_MIN_SIZE |
| 2624 |
socket.SO_VM_SOCKETS_BUFFER_MAX_SIZE |
| 2625 |
socket.VMADDR_CID_ANY |
| 2626 |
socket.VMADDR_PORT_ANY |
| 2627 |
socket.VMADDR_CID_LOCAL |
| 2628 |
socket.VMADDR_CID_HOST |
| 2629 |
socket.VM_SOCKETS_INVALID_VERSION |
| 2630 |
socket.IOCTL_VM_SOCKETS_GET_LOCAL_CID |
| 2631 |
|
| 2632 |
def testCreateSocket(self): |
| 2633 |
with socket.socket(socket.AF_VSOCK, socket.SOCK_STREAM) as s: |
| 2634 |
pass |
| 2635 |
|
| 2636 |
def testSocketBufferSize(self): |
| 2637 |
with socket.socket(socket.AF_VSOCK, socket.SOCK_STREAM) as s: |
| 2638 |
orig_max = s.getsockopt(socket.AF_VSOCK, |
| 2639 |
socket.SO_VM_SOCKETS_BUFFER_MAX_SIZE) |
| 2640 |
orig = s.getsockopt(socket.AF_VSOCK, |
| 2641 |
socket.SO_VM_SOCKETS_BUFFER_SIZE) |
| 2642 |
orig_min = s.getsockopt(socket.AF_VSOCK, |
| 2643 |
socket.SO_VM_SOCKETS_BUFFER_MIN_SIZE) |
| 2644 |
|
| 2645 |
s.setsockopt(socket.AF_VSOCK, |
| 2646 |
socket.SO_VM_SOCKETS_BUFFER_MAX_SIZE, orig_max * 2) |
| 2647 |
s.setsockopt(socket.AF_VSOCK, |
| 2648 |
socket.SO_VM_SOCKETS_BUFFER_SIZE, orig * 2) |
| 2649 |
s.setsockopt(socket.AF_VSOCK, |
| 2650 |
socket.SO_VM_SOCKETS_BUFFER_MIN_SIZE, orig_min * 2) |
| 2651 |
|
| 2652 |
self.assertEqual(orig_max * 2, |
| 2653 |
s.getsockopt(socket.AF_VSOCK, |
| 2654 |
socket.SO_VM_SOCKETS_BUFFER_MAX_SIZE)) |
| 2655 |
self.assertEqual(orig * 2, |
| 2656 |
s.getsockopt(socket.AF_VSOCK, |
| 2657 |
socket.SO_VM_SOCKETS_BUFFER_SIZE)) |
| 2658 |
self.assertEqual(orig_min * 2, |
| 2659 |
s.getsockopt(socket.AF_VSOCK, |
| 2660 |
socket.SO_VM_SOCKETS_BUFFER_MIN_SIZE)) |
| 2661 |
|
| 2662 |
|
| 2663 |
@unittest.skipUnless(hasattr(socket, 'AF_BLUETOOTH'), |
| 2664 |
'Bluetooth sockets required for this test.') |
| 2665 |
class BasicBluetoothTest(unittest.TestCase): |
| 2666 |
|
| 2667 |
def testBluetoothConstants(self): |
| 2668 |
socket.BDADDR_ANY |
| 2669 |
socket.BDADDR_LOCAL |
| 2670 |
socket.AF_BLUETOOTH |
| 2671 |
socket.BTPROTO_RFCOMM |
| 2672 |
socket.SOL_RFCOMM |
| 2673 |
|
| 2674 |
if sys.platform == "win32": |
| 2675 |
socket.SO_BTH_ENCRYPT |
| 2676 |
socket.SO_BTH_MTU |
| 2677 |
socket.SO_BTH_MTU_MAX |
| 2678 |
socket.SO_BTH_MTU_MIN |
| 2679 |
|
| 2680 |
if sys.platform != "win32": |
| 2681 |
socket.BTPROTO_HCI |
| 2682 |
socket.SOL_HCI |
| 2683 |
socket.BTPROTO_L2CAP |
| 2684 |
socket.SOL_L2CAP |
| 2685 |
socket.BTPROTO_SCO |
| 2686 |
socket.SOL_SCO |
| 2687 |
socket.HCI_DATA_DIR |
| 2688 |
|
| 2689 |
if sys.platform == "linux": |
| 2690 |
socket.SOL_BLUETOOTH |
| 2691 |
socket.HCI_DEV_NONE |
| 2692 |
socket.HCI_CHANNEL_RAW |
| 2693 |
socket.HCI_CHANNEL_USER |
| 2694 |
socket.HCI_CHANNEL_MONITOR |
| 2695 |
socket.HCI_CHANNEL_CONTROL |
| 2696 |
socket.HCI_CHANNEL_LOGGING |
| 2697 |
socket.HCI_TIME_STAMP |
| 2698 |
socket.BT_SECURITY |
| 2699 |
socket.BT_SECURITY_SDP |
| 2700 |
socket.BT_FLUSHABLE |
| 2701 |
socket.BT_POWER |
| 2702 |
socket.BT_CHANNEL_POLICY |
| 2703 |
socket.BT_CHANNEL_POLICY_BREDR_ONLY |
| 2704 |
if hasattr(socket, 'BT_PHY'): |
| 2705 |
socket.BT_PHY_BR_1M_1SLOT |
| 2706 |
if hasattr(socket, 'BT_MODE'): |
| 2707 |
socket.BT_MODE_BASIC |
| 2708 |
if hasattr(socket, 'BT_VOICE'): |
| 2709 |
socket.BT_VOICE_TRANSPARENT |
| 2710 |
socket.BT_VOICE_CVSD_16BIT |
| 2711 |
socket.L2CAP_LM |
| 2712 |
socket.L2CAP_LM_MASTER |
| 2713 |
socket.L2CAP_LM_AUTH |
| 2714 |
|
| 2715 |
if sys.platform in ("linux", "freebsd"): |
| 2716 |
socket.BDADDR_BREDR |
| 2717 |
socket.BDADDR_LE_PUBLIC |
| 2718 |
socket.BDADDR_LE_RANDOM |
| 2719 |
socket.HCI_FILTER |
| 2720 |
|
| 2721 |
if sys.platform.startswith(("freebsd", "netbsd", "dragonfly")): |
| 2722 |
socket.SO_L2CAP_IMTU |
| 2723 |
socket.SO_L2CAP_FLUSH |
| 2724 |
socket.SO_RFCOMM_MTU |
| 2725 |
socket.SO_RFCOMM_FC_INFO |
| 2726 |
socket.SO_SCO_MTU |
| 2727 |
|
| 2728 |
if sys.platform == "freebsd": |
| 2729 |
socket.SO_SCO_CONNINFO |
| 2730 |
|
| 2731 |
if sys.platform.startswith(("netbsd", "dragonfly")): |
| 2732 |
socket.SO_HCI_EVT_FILTER |
| 2733 |
socket.SO_HCI_PKT_FILTER |
| 2734 |
socket.SO_L2CAP_IQOS |
| 2735 |
socket.SO_L2CAP_LM |
| 2736 |
socket.L2CAP_LM_AUTH |
| 2737 |
socket.SO_RFCOMM_LM |
| 2738 |
socket.RFCOMM_LM_AUTH |
| 2739 |
socket.SO_SCO_HANDLE |
| 2740 |
|
| 2741 |
@unittest.skipUnless(HAVE_SOCKET_BLUETOOTH, |
| 2742 |
'Bluetooth sockets required for this test.') |
| 2743 |
class BluetoothTest(unittest.TestCase): |
| 2744 |
|
| 2745 |
def testCreateRfcommSocket(self): |
| 2746 |
with socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM) as s: |
| 2747 |
pass |
| 2748 |
|
| 2749 |
@unittest.skipIf(sys.platform == "win32", "windows does not support L2CAP sockets") |
| 2750 |
def testCreateL2capSocket(self): |
| 2751 |
with socket.socket(socket.AF_BLUETOOTH, socket.SOCK_SEQPACKET, socket.BTPROTO_L2CAP) as s: |
| 2752 |
pass |
| 2753 |
|
| 2754 |
@unittest.skipIf(sys.platform == "win32", "windows does not support HCI sockets") |
| 2755 |
def testCreateHciSocket(self): |
| 2756 |
with socket.socket(socket.AF_BLUETOOTH, socket.SOCK_RAW, socket.BTPROTO_HCI) as s: |
| 2757 |
pass |
| 2758 |
|
| 2759 |
@unittest.skipIf(sys.platform == "win32", "windows does not support SCO sockets") |
| 2760 |
def testCreateScoSocket(self): |
| 2761 |
with socket.socket(socket.AF_BLUETOOTH, socket.SOCK_SEQPACKET, socket.BTPROTO_SCO) as s: |
| 2762 |
pass |
| 2763 |
|
| 2764 |
@unittest.skipUnless(HAVE_SOCKET_BLUETOOTH_L2CAP, 'Bluetooth L2CAP sockets required for this test') |
| 2765 |
def testBindLeAttL2capSocket(self): |
| 2766 |
BDADDR_LE_PUBLIC = support.get_attribute(socket, 'BDADDR_LE_PUBLIC') |
| 2767 |
with socket.socket(socket.AF_BLUETOOTH, socket.SOCK_SEQPACKET, socket.BTPROTO_L2CAP) as f: |
| 2768 |
# ATT is the only CID allowed in userspace by the Linux kernel |
| 2769 |
CID_ATT = 4 |
| 2770 |
f.bind((socket.BDADDR_ANY, 0, CID_ATT, BDADDR_LE_PUBLIC)) |
| 2771 |
addr = f.getsockname() |
| 2772 |
self.assertEqual(addr, (socket.BDADDR_ANY, 0, CID_ATT, BDADDR_LE_PUBLIC)) |
| 2773 |
|
| 2774 |
@unittest.skipUnless(HAVE_SOCKET_BLUETOOTH_L2CAP, 'Bluetooth L2CAP sockets required for this test') |
| 2775 |
def testBindLePsmL2capSocket(self): |
| 2776 |
BDADDR_LE_RANDOM = support.get_attribute(socket, 'BDADDR_LE_RANDOM') |
| 2777 |
with socket.socket(socket.AF_BLUETOOTH, socket.SOCK_SEQPACKET, socket.BTPROTO_L2CAP) as f: |
| 2778 |
# First user PSM in LE L2CAP |
| 2779 |
psm = 0x80 |
| 2780 |
f.bind((socket.BDADDR_ANY, psm, 0, BDADDR_LE_RANDOM)) |
| 2781 |
addr = f.getsockname() |
| 2782 |
self.assertEqual(addr, (socket.BDADDR_ANY, psm, 0, BDADDR_LE_RANDOM)) |
| 2783 |
|
| 2784 |
@unittest.skipUnless(HAVE_SOCKET_BLUETOOTH_L2CAP, 'Bluetooth L2CAP sockets required for this test') |
| 2785 |
def testBindBrEdrL2capSocket(self): |
| 2786 |
with socket.socket(socket.AF_BLUETOOTH, socket.SOCK_SEQPACKET, socket.BTPROTO_L2CAP) as f: |
| 2787 |
# First user PSM in BR/EDR L2CAP |
| 2788 |
psm = 0x1001 |
| 2789 |
f.bind((socket.BDADDR_ANY, psm)) |
| 2790 |
addr = f.getsockname() |
| 2791 |
self.assertEqual(addr, (socket.BDADDR_ANY, psm)) |
| 2792 |
|
| 2793 |
@unittest.skipUnless(HAVE_SOCKET_BLUETOOTH_L2CAP, 'Bluetooth L2CAP sockets required for this test') |
| 2794 |
def testBadL2capAddr(self): |
| 2795 |
with socket.socket(socket.AF_BLUETOOTH, socket.SOCK_SEQPACKET, socket.BTPROTO_L2CAP) as f: |
| 2796 |
with self.assertRaises(OSError): |
| 2797 |
f.bind((socket.BDADDR_ANY, 0, 0, 0, 0)) |
| 2798 |
with self.assertRaises(OSError): |
| 2799 |
f.bind((socket.BDADDR_ANY,)) |
| 2800 |
with self.assertRaises(OSError): |
| 2801 |
f.bind(socket.BDADDR_ANY) |
| 2802 |
with self.assertRaises(OSError): |
| 2803 |
f.bind((socket.BDADDR_ANY.encode(), 0x1001)) |
| 2804 |
with self.assertRaises(OSError): |
| 2805 |
f.bind(('\ud812', 0x1001)) |
| 2806 |
|
| 2807 |
def testBindRfcommSocket(self): |
| 2808 |
with socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM) as s: |
| 2809 |
channel = 0 |
| 2810 |
try: |
| 2811 |
s.bind((socket.BDADDR_ANY, channel)) |
| 2812 |
except OSError as err: |
| 2813 |
if sys.platform == 'win32' and err.winerror == 10050: |
| 2814 |
self.skipTest(str(err)) |
| 2815 |
raise |
| 2816 |
addr = s.getsockname() |
| 2817 |
self.assertEqual(addr, (mock.ANY, channel)) |
| 2818 |
self.assertRegex(addr[0], r'(?i)[0-9a-f]{2}(?::[0-9a-f]{2}){4}') |
| 2819 |
if sys.platform != 'win32': |
| 2820 |
self.assertEqual(addr, (socket.BDADDR_ANY, channel)) |
| 2821 |
with socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM) as s: |
| 2822 |
s.bind(addr) |
| 2823 |
addr2 = s.getsockname() |
| 2824 |
self.assertEqual(addr2, addr) |
| 2825 |
|
| 2826 |
def testBadRfcommAddr(self): |
| 2827 |
with socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM) as s: |
| 2828 |
channel = 0 |
| 2829 |
with self.assertRaises(OSError): |
| 2830 |
s.bind((socket.BDADDR_ANY.encode(), channel)) |
| 2831 |
with self.assertRaises(OSError): |
| 2832 |
s.bind((socket.BDADDR_ANY,)) |
| 2833 |
with self.assertRaises(OSError): |
| 2834 |
s.bind((socket.BDADDR_ANY, channel, 0)) |
| 2835 |
with self.assertRaises(OSError): |
| 2836 |
s.bind((socket.BDADDR_ANY + '\0', channel)) |
| 2837 |
with self.assertRaises(OSError): |
| 2838 |
s.bind('\ud812') |
| 2839 |
with self.assertRaises(OSError): |
| 2840 |
s.bind(('invalid', channel)) |
| 2841 |
|
| 2842 |
@unittest.skipUnless(hasattr(socket, 'BTPROTO_HCI'), 'Bluetooth HCI sockets required for this test') |
| 2843 |
def testBindHciSocket(self): |
| 2844 |
if sys.platform.startswith(('netbsd', 'dragonfly', 'freebsd')): |
| 2845 |
with socket.socket(socket.AF_BLUETOOTH, socket.SOCK_RAW, socket.BTPROTO_HCI) as s: |
| 2846 |
s.bind(socket.BDADDR_ANY) |
| 2847 |
addr = s.getsockname() |
| 2848 |
self.assertEqual(addr, socket.BDADDR_ANY) |
| 2849 |
else: |
| 2850 |
dev = 0 |
| 2851 |
with socket.socket(socket.AF_BLUETOOTH, socket.SOCK_RAW, socket.BTPROTO_HCI) as s: |
| 2852 |
try: |
| 2853 |
s.bind((dev,)) |
| 2854 |
except OSError as err: |
| 2855 |
if err.errno in (errno.EINVAL, errno.ENODEV): |
| 2856 |
self.skipTest(str(err)) |
| 2857 |
raise |
| 2858 |
addr = s.getsockname() |
| 2859 |
self.assertEqual(addr, dev) |
| 2860 |
|
| 2861 |
with (self.subTest('integer'), |
| 2862 |
socket.socket(socket.AF_BLUETOOTH, socket.SOCK_RAW, socket.BTPROTO_HCI) as s): |
| 2863 |
s.bind(dev) |
| 2864 |
addr = s.getsockname() |
| 2865 |
self.assertEqual(addr, dev) |
| 2866 |
|
| 2867 |
with (self.subTest('channel=HCI_CHANNEL_RAW'), |
| 2868 |
socket.socket(socket.AF_BLUETOOTH, socket.SOCK_RAW, socket.BTPROTO_HCI) as s): |
| 2869 |
channel = socket.HCI_CHANNEL_RAW |
| 2870 |
s.bind((dev, channel)) |
| 2871 |
addr = s.getsockname() |
| 2872 |
self.assertEqual(addr, dev) |
| 2873 |
|
| 2874 |
with (self.subTest('channel=HCI_CHANNEL_USER'), |
| 2875 |
socket.socket(socket.AF_BLUETOOTH, socket.SOCK_RAW, socket.BTPROTO_HCI) as s): |
| 2876 |
channel = socket.HCI_CHANNEL_USER |
| 2877 |
try: |
| 2878 |
s.bind((dev, channel)) |
| 2879 |
except OSError as err: |
| 2880 |
# Needs special permissions. |
| 2881 |
if err.errno in (errno.EPERM, errno.EBUSY, errno.ERFKILL): |
| 2882 |
self.skipTest(str(err)) |
| 2883 |
raise |
| 2884 |
addr = s.getsockname() |
| 2885 |
self.assertEqual(addr, (dev, channel)) |
| 2886 |
|
| 2887 |
@unittest.skipUnless(hasattr(socket, 'BTPROTO_HCI'), 'Bluetooth HCI sockets required for this test') |
| 2888 |
def testBadHciAddr(self): |
| 2889 |
with socket.socket(socket.AF_BLUETOOTH, socket.SOCK_RAW, socket.BTPROTO_HCI) as s: |
| 2890 |
if sys.platform.startswith(('netbsd', 'dragonfly', 'freebsd')): |
| 2891 |
with self.assertRaises(OSError): |
| 2892 |
s.bind(socket.BDADDR_ANY.encode()) |
| 2893 |
with self.assertRaises(OSError): |
| 2894 |
s.bind((socket.BDADDR_ANY,)) |
| 2895 |
with self.assertRaises(OSError): |
| 2896 |
s.bind(socket.BDADDR_ANY + '\0') |
| 2897 |
with self.assertRaises((ValueError, OSError)): |
| 2898 |
s.bind(socket.BDADDR_ANY + ' '*100) |
| 2899 |
with self.assertRaises(OSError): |
| 2900 |
s.bind('\ud812') |
| 2901 |
with self.assertRaises(OSError): |
| 2902 |
s.bind('invalid') |
| 2903 |
with self.assertRaises(OSError): |
| 2904 |
s.bind(b'invalid') |
| 2905 |
else: |
| 2906 |
dev = 0 |
| 2907 |
with self.assertRaises(OSError): |
| 2908 |
s.bind(()) |
| 2909 |
with self.assertRaises(OSError): |
| 2910 |
s.bind((dev, socket.HCI_CHANNEL_RAW, 0, 0)) |
| 2911 |
with self.assertRaises(OSError): |
| 2912 |
s.bind(socket.BDADDR_ANY) |
| 2913 |
with self.assertRaises(OSError): |
| 2914 |
s.bind(socket.BDADDR_ANY.encode()) |
| 2915 |
|
| 2916 |
@unittest.skipUnless(hasattr(socket, 'BTPROTO_SCO'), 'Bluetooth SCO sockets required for this test') |
| 2917 |
def testBindScoSocket(self): |
| 2918 |
with socket.socket(socket.AF_BLUETOOTH, socket.SOCK_SEQPACKET, socket.BTPROTO_SCO) as s: |
| 2919 |
s.bind(socket.BDADDR_ANY) |
| 2920 |
addr = s.getsockname() |
| 2921 |
self.assertEqual(addr, socket.BDADDR_ANY) |
| 2922 |
|
| 2923 |
with socket.socket(socket.AF_BLUETOOTH, socket.SOCK_SEQPACKET, socket.BTPROTO_SCO) as s: |
| 2924 |
s.bind(socket.BDADDR_ANY.encode()) |
| 2925 |
addr = s.getsockname() |
| 2926 |
self.assertEqual(addr, socket.BDADDR_ANY) |
| 2927 |
|
| 2928 |
@unittest.skipUnless(hasattr(socket, 'BTPROTO_SCO'), 'Bluetooth SCO sockets required for this test') |
| 2929 |
def testBadScoAddr(self): |
| 2930 |
with socket.socket(socket.AF_BLUETOOTH, socket.SOCK_SEQPACKET, socket.BTPROTO_SCO) as s: |
| 2931 |
with self.assertRaises(OSError): |
| 2932 |
s.bind((socket.BDADDR_ANY,)) |
| 2933 |
with self.assertRaises(OSError): |
| 2934 |
s.bind((socket.BDADDR_ANY.encode(),)) |
| 2935 |
with self.assertRaises(ValueError): |
| 2936 |
s.bind(socket.BDADDR_ANY + '\0') |
| 2937 |
with self.assertRaises(ValueError): |
| 2938 |
s.bind(socket.BDADDR_ANY.encode() + b'\0') |
| 2939 |
with self.assertRaises(UnicodeEncodeError): |
| 2940 |
s.bind('\ud812') |
| 2941 |
with self.assertRaises(OSError): |
| 2942 |
s.bind('invalid') |
| 2943 |
with self.assertRaises(OSError): |
| 2944 |
s.bind(b'invalid') |
| 2945 |
|
| 2946 |
|
| 2947 |
@unittest.skipUnless(HAVE_SOCKET_HYPERV, |
| 2948 |
'Hyper-V sockets required for this test.') |
| 2949 |
class BasicHyperVTest(unittest.TestCase): |
| 2950 |
|
| 2951 |
def testHyperVConstants(self): |
| 2952 |
socket.HVSOCKET_CONNECT_TIMEOUT |
| 2953 |
socket.HVSOCKET_CONNECT_TIMEOUT_MAX |
| 2954 |
socket.HVSOCKET_CONNECTED_SUSPEND |
| 2955 |
socket.HVSOCKET_ADDRESS_FLAG_PASSTHRU |
| 2956 |
socket.HV_GUID_ZERO |
| 2957 |
socket.HV_GUID_WILDCARD |
| 2958 |
socket.HV_GUID_BROADCAST |
| 2959 |
socket.HV_GUID_CHILDREN |
| 2960 |
socket.HV_GUID_LOOPBACK |
| 2961 |
socket.HV_GUID_PARENT |
| 2962 |
|
| 2963 |
def testCreateHyperVSocketWithUnknownProtoFailure(self): |
| 2964 |
expected = r"\[WinError 10041\]" |
| 2965 |
with self.assertRaisesRegex(OSError, expected): |
| 2966 |
socket.socket(socket.AF_HYPERV, socket.SOCK_STREAM) |
| 2967 |
|
| 2968 |
def testCreateHyperVSocketAddrNotTupleFailure(self): |
| 2969 |
expected = "connect(): AF_HYPERV address must be tuple, not str" |
| 2970 |
with socket.socket(socket.AF_HYPERV, socket.SOCK_STREAM, socket.HV_PROTOCOL_RAW) as s: |
| 2971 |
with self.assertRaisesRegex(TypeError, re.escape(expected)): |
| 2972 |
s.connect(socket.HV_GUID_ZERO) |
| 2973 |
|
| 2974 |
def testCreateHyperVSocketAddrNotTupleOf2StrsFailure(self): |
| 2975 |
expected = "AF_HYPERV address must be a str tuple (vm_id, service_id)" |
| 2976 |
with socket.socket(socket.AF_HYPERV, socket.SOCK_STREAM, socket.HV_PROTOCOL_RAW) as s: |
| 2977 |
with self.assertRaisesRegex(TypeError, re.escape(expected)): |
| 2978 |
s.connect((socket.HV_GUID_ZERO,)) |
| 2979 |
|
| 2980 |
def testCreateHyperVSocketAddrNotTupleOfStrsFailure(self): |
| 2981 |
expected = "AF_HYPERV address must be a str tuple (vm_id, service_id)" |
| 2982 |
with socket.socket(socket.AF_HYPERV, socket.SOCK_STREAM, socket.HV_PROTOCOL_RAW) as s: |
| 2983 |
with self.assertRaisesRegex(TypeError, re.escape(expected)): |
| 2984 |
s.connect((1, 2)) |
| 2985 |
|
| 2986 |
def testCreateHyperVSocketAddrVmIdNotValidUUIDFailure(self): |
| 2987 |
expected = "connect(): AF_HYPERV address vm_id is not a valid UUID string" |
| 2988 |
with socket.socket(socket.AF_HYPERV, socket.SOCK_STREAM, socket.HV_PROTOCOL_RAW) as s: |
| 2989 |
with self.assertRaisesRegex(ValueError, re.escape(expected)): |
| 2990 |
s.connect(("00", socket.HV_GUID_ZERO)) |
| 2991 |
|
| 2992 |
def testCreateHyperVSocketAddrServiceIdNotValidUUIDFailure(self): |
| 2993 |
expected = "connect(): AF_HYPERV address service_id is not a valid UUID string" |
| 2994 |
with socket.socket(socket.AF_HYPERV, socket.SOCK_STREAM, socket.HV_PROTOCOL_RAW) as s: |
| 2995 |
with self.assertRaisesRegex(ValueError, re.escape(expected)): |
| 2996 |
s.connect((socket.HV_GUID_ZERO, "00")) |
| 2997 |
|
| 2998 |
|
| 2999 |
class BasicTCPTest(SocketConnectedTest): |
| 3000 |
|
| 3001 |
def __init__(self, methodName='runTest'): |
| 3002 |
SocketConnectedTest.__init__(self, methodName=methodName) |
| 3003 |
|
| 3004 |
def testRecv(self): |
| 3005 |
# Testing large receive over TCP |
| 3006 |
msg = self.cli_conn.recv(1024) |
| 3007 |
self.assertEqual(msg, MSG) |
| 3008 |
|
| 3009 |
def _testRecv(self): |
| 3010 |
self.serv_conn.send(MSG) |
| 3011 |
|
| 3012 |
def testOverFlowRecv(self): |
| 3013 |
# Testing receive in chunks over TCP |
| 3014 |
seg1 = self.cli_conn.recv(len(MSG) - 3) |
| 3015 |
seg2 = self.cli_conn.recv(1024) |
| 3016 |
msg = seg1 + seg2 |
| 3017 |
self.assertEqual(msg, MSG) |
| 3018 |
|
| 3019 |
def _testOverFlowRecv(self): |
| 3020 |
self.serv_conn.send(MSG) |
| 3021 |
|
| 3022 |
def testRecvFrom(self): |
| 3023 |
# Testing large recvfrom() over TCP |
| 3024 |
msg, addr = self.cli_conn.recvfrom(1024) |
| 3025 |
self.assertEqual(msg, MSG) |
| 3026 |
|
| 3027 |
def _testRecvFrom(self): |
| 3028 |
self.serv_conn.send(MSG) |
| 3029 |
|
| 3030 |
def testOverFlowRecvFrom(self): |
| 3031 |
# Testing recvfrom() in chunks over TCP |
| 3032 |
seg1, addr = self.cli_conn.recvfrom(len(MSG)-3) |
| 3033 |
seg2, addr = self.cli_conn.recvfrom(1024) |
| 3034 |
msg = seg1 + seg2 |
| 3035 |
self.assertEqual(msg, MSG) |
| 3036 |
|
| 3037 |
def _testOverFlowRecvFrom(self): |
| 3038 |
self.serv_conn.send(MSG) |
| 3039 |
|
| 3040 |
def testSendAll(self): |
| 3041 |
# Testing sendall() with a 2048 byte string over TCP |
| 3042 |
msg = b'' |
| 3043 |
while 1: |
| 3044 |
read = self.cli_conn.recv(1024) |
| 3045 |
if not read: |
| 3046 |
break |
| 3047 |
msg += read |
| 3048 |
self.assertEqual(msg, b'f' * 2048) |
| 3049 |
|
| 3050 |
def _testSendAll(self): |
| 3051 |
big_chunk = b'f' * 2048 |
| 3052 |
self.serv_conn.sendall(big_chunk) |
| 3053 |
|
| 3054 |
def testFromFd(self): |
| 3055 |
# Testing fromfd() |
| 3056 |
fd = self.cli_conn.fileno() |
| 3057 |
sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM) |
| 3058 |
self.addCleanup(sock.close) |
| 3059 |
self.assertIsInstance(sock, socket.socket) |
| 3060 |
msg = sock.recv(1024) |
| 3061 |
self.assertEqual(msg, MSG) |
| 3062 |
|
| 3063 |
def _testFromFd(self): |
| 3064 |
self.serv_conn.send(MSG) |
| 3065 |
|
| 3066 |
def testDup(self): |
| 3067 |
# Testing dup() |
| 3068 |
sock = self.cli_conn.dup() |
| 3069 |
self.addCleanup(sock.close) |
| 3070 |
msg = sock.recv(1024) |
| 3071 |
self.assertEqual(msg, MSG) |
| 3072 |
|
| 3073 |
def _testDup(self): |
| 3074 |
self.serv_conn.send(MSG) |
| 3075 |
|
| 3076 |
def check_shutdown(self): |
| 3077 |
# Test shutdown() helper |
| 3078 |
msg = self.cli_conn.recv(1024) |
| 3079 |
self.assertEqual(msg, MSG) |
| 3080 |
# wait for _testShutdown[_overflow] to finish: on OS X, when the server |
| 3081 |
# closes the connection the client also becomes disconnected, |
| 3082 |
# and the client's shutdown call will fail. (Issue #4397.) |
| 3083 |
self.done.wait() |
| 3084 |
|
| 3085 |
def testShutdown(self): |
| 3086 |
self.check_shutdown() |
| 3087 |
|
| 3088 |
def _testShutdown(self): |
| 3089 |
self.serv_conn.send(MSG) |
| 3090 |
self.serv_conn.shutdown(2) |
| 3091 |
|
| 3092 |
@support.cpython_only |
| 3093 |
@unittest.skipIf(_testcapi is None, "requires _testcapi") |
| 3094 |
def testShutdown_overflow(self): |
| 3095 |
self.check_shutdown() |
| 3096 |
|
| 3097 |
@support.cpython_only |
| 3098 |
@unittest.skipIf(_testcapi is None, "requires _testcapi") |
| 3099 |
def _testShutdown_overflow(self): |
| 3100 |
import _testcapi |
| 3101 |
self.serv_conn.send(MSG) |
| 3102 |
# Issue 15989 |
| 3103 |
self.assertRaises(OverflowError, self.serv_conn.shutdown, |
| 3104 |
_testcapi.INT_MAX + 1) |
| 3105 |
self.assertRaises(OverflowError, self.serv_conn.shutdown, |
| 3106 |
2 + (_testcapi.UINT_MAX + 1)) |
| 3107 |
self.serv_conn.shutdown(2) |
| 3108 |
|
| 3109 |
def testDetach(self): |
| 3110 |
# Testing detach() |
| 3111 |
fileno = self.cli_conn.fileno() |
| 3112 |
f = self.cli_conn.detach() |
| 3113 |
self.assertEqual(f, fileno) |
| 3114 |
# cli_conn cannot be used anymore... |
| 3115 |
self.assertTrue(self.cli_conn._closed) |
| 3116 |
self.assertRaises(OSError, self.cli_conn.recv, 1024) |
| 3117 |
self.cli_conn.close() |
| 3118 |
# ...but we can create another socket using the (still open) |
| 3119 |
# file descriptor |
| 3120 |
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, fileno=f) |
| 3121 |
self.addCleanup(sock.close) |
| 3122 |
msg = sock.recv(1024) |
| 3123 |
self.assertEqual(msg, MSG) |
| 3124 |
|
| 3125 |
def _testDetach(self): |
| 3126 |
self.serv_conn.send(MSG) |
| 3127 |
|
| 3128 |
|
| 3129 |
class BasicUDPTest(ThreadedUDPSocketTest): |
| 3130 |
|
| 3131 |
def __init__(self, methodName='runTest'): |
| 3132 |
ThreadedUDPSocketTest.__init__(self, methodName=methodName) |
| 3133 |
|
| 3134 |
def testSendtoAndRecv(self): |
| 3135 |
# Testing sendto() and Recv() over UDP |
| 3136 |
msg = self.serv.recv(len(MSG)) |
| 3137 |
self.assertEqual(msg, MSG) |
| 3138 |
|
| 3139 |
def _testSendtoAndRecv(self): |
| 3140 |
self.cli.sendto(MSG, 0, (HOST, self.port)) |
| 3141 |
|
| 3142 |
def testRecvFrom(self): |
| 3143 |
# Testing recvfrom() over UDP |
| 3144 |
msg, addr = self.serv.recvfrom(len(MSG)) |
| 3145 |
self.assertEqual(msg, MSG) |
| 3146 |
|
| 3147 |
def _testRecvFrom(self): |
| 3148 |
self.cli.sendto(MSG, 0, (HOST, self.port)) |
| 3149 |
|
| 3150 |
def testRecvFromNegative(self): |
| 3151 |
# Negative lengths passed to recvfrom should give ValueError. |
| 3152 |
self.assertRaises(ValueError, self.serv.recvfrom, -1) |
| 3153 |
|
| 3154 |
def _testRecvFromNegative(self): |
| 3155 |
self.cli.sendto(MSG, 0, (HOST, self.port)) |
| 3156 |
|
| 3157 |
|
| 3158 |
@unittest.skipUnless(HAVE_SOCKET_UDPLITE, |
| 3159 |
'UDPLITE sockets required for this test.') |
| 3160 |
class BasicUDPLITETest(ThreadedUDPLITESocketTest): |
| 3161 |
|
| 3162 |
def __init__(self, methodName='runTest'): |
| 3163 |
ThreadedUDPLITESocketTest.__init__(self, methodName=methodName) |
| 3164 |
|
| 3165 |
def testSendtoAndRecv(self): |
| 3166 |
# Testing sendto() and Recv() over UDPLITE |
| 3167 |
msg = self.serv.recv(len(MSG)) |
| 3168 |
self.assertEqual(msg, MSG) |
| 3169 |
|
| 3170 |
def _testSendtoAndRecv(self): |
| 3171 |
self.cli.sendto(MSG, 0, (HOST, self.port)) |
| 3172 |
|
| 3173 |
def testRecvFrom(self): |
| 3174 |
# Testing recvfrom() over UDPLITE |
| 3175 |
msg, addr = self.serv.recvfrom(len(MSG)) |
| 3176 |
self.assertEqual(msg, MSG) |
| 3177 |
|
| 3178 |
def _testRecvFrom(self): |
| 3179 |
self.cli.sendto(MSG, 0, (HOST, self.port)) |
| 3180 |
|
| 3181 |
def testRecvFromNegative(self): |
| 3182 |
# Negative lengths passed to recvfrom should give ValueError. |
| 3183 |
self.assertRaises(ValueError, self.serv.recvfrom, -1) |
| 3184 |
|
| 3185 |
def _testRecvFromNegative(self): |
| 3186 |
self.cli.sendto(MSG, 0, (HOST, self.port)) |
| 3187 |
|
| 3188 |
# Tests for the sendmsg()/recvmsg() interface. Where possible, the |
| 3189 |
# same test code is used with different families and types of socket |
| 3190 |
# (e.g. stream, datagram), and tests using recvmsg() are repeated |
| 3191 |
# using recvmsg_into(). |
| 3192 |
# |
| 3193 |
# The generic test classes such as SendmsgTests and |
| 3194 |
# RecvmsgGenericTests inherit from SendrecvmsgBase and expect to be |
| 3195 |
# supplied with sockets cli_sock and serv_sock representing the |
| 3196 |
# client's and the server's end of the connection respectively, and |
| 3197 |
# attributes cli_addr and serv_addr holding their (numeric where |
| 3198 |
# appropriate) addresses. |
| 3199 |
# |
| 3200 |
# The final concrete test classes combine these with subclasses of |
| 3201 |
# SocketTestBase which set up client and server sockets of a specific |
| 3202 |
# type, and with subclasses of SendrecvmsgBase such as |
| 3203 |
# SendrecvmsgDgramBase and SendrecvmsgConnectedBase which map these |
| 3204 |
# sockets to cli_sock and serv_sock and override the methods and |
| 3205 |
# attributes of SendrecvmsgBase to fill in destination addresses if |
| 3206 |
# needed when sending, check for specific flags in msg_flags, etc. |
| 3207 |
# |
| 3208 |
# RecvmsgIntoMixin provides a version of doRecvmsg() implemented using |
| 3209 |
# recvmsg_into(). |
| 3210 |
|
| 3211 |
# XXX: like the other datagram (UDP) tests in this module, the code |
| 3212 |
# here assumes that datagram delivery on the local machine will be |
| 3213 |
# reliable. |
| 3214 |
|
| 3215 |
class SendrecvmsgBase: |
| 3216 |
# Base class for sendmsg()/recvmsg() tests. |
| 3217 |
|
| 3218 |
# Time in seconds to wait before considering a test failed, or |
| 3219 |
# None for no timeout. Not all tests actually set a timeout. |
| 3220 |
fail_timeout = support.LOOPBACK_TIMEOUT |
| 3221 |
|
| 3222 |
def setUp(self): |
| 3223 |
self.misc_event = threading.Event() |
| 3224 |
super().setUp() |
| 3225 |
|
| 3226 |
def sendToServer(self, msg): |
| 3227 |
# Send msg to the server. |
| 3228 |
return self.cli_sock.send(msg) |
| 3229 |
|
| 3230 |
# Tuple of alternative default arguments for sendmsg() when called |
| 3231 |
# via sendmsgToServer() (e.g. to include a destination address). |
| 3232 |
sendmsg_to_server_defaults = () |
| 3233 |
|
| 3234 |
def sendmsgToServer(self, *args): |
| 3235 |
# Call sendmsg() on self.cli_sock with the given arguments, |
| 3236 |
# filling in any arguments which are not supplied with the |
| 3237 |
# corresponding items of self.sendmsg_to_server_defaults, if |
| 3238 |
# any. |
| 3239 |
return self.cli_sock.sendmsg( |
| 3240 |
*(args + self.sendmsg_to_server_defaults[len(args):])) |
| 3241 |
|
| 3242 |
def doRecvmsg(self, sock, bufsize, *args): |
| 3243 |
# Call recvmsg() on sock with given arguments and return its |
| 3244 |
# result. Should be used for tests which can use either |
| 3245 |
# recvmsg() or recvmsg_into() - RecvmsgIntoMixin overrides |
| 3246 |
# this method with one which emulates it using recvmsg_into(), |
| 3247 |
# thus allowing the same test to be used for both methods. |
| 3248 |
result = sock.recvmsg(bufsize, *args) |
| 3249 |
self.registerRecvmsgResult(result) |
| 3250 |
return result |
| 3251 |
|
| 3252 |
def registerRecvmsgResult(self, result): |
| 3253 |
# Called by doRecvmsg() with the return value of recvmsg() or |
| 3254 |
# recvmsg_into(). Can be overridden to arrange cleanup based |
| 3255 |
# on the returned ancillary data, for instance. |
| 3256 |
pass |
| 3257 |
|
| 3258 |
def checkRecvmsgAddress(self, addr1, addr2): |
| 3259 |
# Called to compare the received address with the address of |
| 3260 |
# the peer. |
| 3261 |
self.assertEqual(addr1, addr2) |
| 3262 |
|
| 3263 |
# Flags that are normally unset in msg_flags |
| 3264 |
msg_flags_common_unset = 0 |
| 3265 |
for name in ("MSG_CTRUNC", "MSG_OOB"): |
| 3266 |
msg_flags_common_unset |= getattr(socket, name, 0) |
| 3267 |
|
| 3268 |
# Flags that are normally set |
| 3269 |
msg_flags_common_set = 0 |
| 3270 |
|
| 3271 |
# Flags set when a complete record has been received (e.g. MSG_EOR |
| 3272 |
# for SCTP) |
| 3273 |
msg_flags_eor_indicator = 0 |
| 3274 |
|
| 3275 |
# Flags set when a complete record has not been received |
| 3276 |
# (e.g. MSG_TRUNC for datagram sockets) |
| 3277 |
msg_flags_non_eor_indicator = 0 |
| 3278 |
|
| 3279 |
def checkFlags(self, flags, eor=None, checkset=0, checkunset=0, ignore=0): |
| 3280 |
# Method to check the value of msg_flags returned by recvmsg[_into](). |
| 3281 |
# |
| 3282 |
# Checks that all bits in msg_flags_common_set attribute are |
| 3283 |
# set in "flags" and all bits in msg_flags_common_unset are |
| 3284 |
# unset. |
| 3285 |
# |
| 3286 |
# The "eor" argument specifies whether the flags should |
| 3287 |
# indicate that a full record (or datagram) has been received. |
| 3288 |
# If "eor" is None, no checks are done; otherwise, checks |
| 3289 |
# that: |
| 3290 |
# |
| 3291 |
# * if "eor" is true, all bits in msg_flags_eor_indicator are |
| 3292 |
# set and all bits in msg_flags_non_eor_indicator are unset |
| 3293 |
# |
| 3294 |
# * if "eor" is false, all bits in msg_flags_non_eor_indicator |
| 3295 |
# are set and all bits in msg_flags_eor_indicator are unset |
| 3296 |
# |
| 3297 |
# If "checkset" and/or "checkunset" are supplied, they require |
| 3298 |
# the given bits to be set or unset respectively, overriding |
| 3299 |
# what the attributes require for those bits. |
| 3300 |
# |
| 3301 |
# If any bits are set in "ignore", they will not be checked, |
| 3302 |
# regardless of the other inputs. |
| 3303 |
# |
| 3304 |
# Will raise Exception if the inputs require a bit to be both |
| 3305 |
# set and unset, and it is not ignored. |
| 3306 |
|
| 3307 |
defaultset = self.msg_flags_common_set |
| 3308 |
defaultunset = self.msg_flags_common_unset |
| 3309 |
|
| 3310 |
if eor: |
| 3311 |
defaultset |= self.msg_flags_eor_indicator |
| 3312 |
defaultunset |= self.msg_flags_non_eor_indicator |
| 3313 |
elif eor is not None: |
| 3314 |
defaultset |= self.msg_flags_non_eor_indicator |
| 3315 |
defaultunset |= self.msg_flags_eor_indicator |
| 3316 |
|
| 3317 |
# Function arguments override defaults |
| 3318 |
defaultset &= ~checkunset |
| 3319 |
defaultunset &= ~checkset |
| 3320 |
|
| 3321 |
# Merge arguments with remaining defaults, and check for conflicts |
| 3322 |
checkset |= defaultset |
| 3323 |
checkunset |= defaultunset |
| 3324 |
inboth = checkset & checkunset & ~ignore |
| 3325 |
if inboth: |
| 3326 |
raise Exception("contradictory set, unset requirements for flags " |
| 3327 |
"{0:#x}".format(inboth)) |
| 3328 |
|
| 3329 |
# Compare with given msg_flags value |
| 3330 |
mask = (checkset | checkunset) & ~ignore |
| 3331 |
self.assertEqual(flags & mask, checkset & mask) |
| 3332 |
|
| 3333 |
|
| 3334 |
class RecvmsgIntoMixin(SendrecvmsgBase): |
| 3335 |
# Mixin to implement doRecvmsg() using recvmsg_into(). |
| 3336 |
|
| 3337 |
def doRecvmsg(self, sock, bufsize, *args): |
| 3338 |
buf = bytearray(bufsize) |
| 3339 |
result = sock.recvmsg_into([buf], *args) |
| 3340 |
self.registerRecvmsgResult(result) |
| 3341 |
self.assertGreaterEqual(result[0], 0) |
| 3342 |
self.assertLessEqual(result[0], bufsize) |
| 3343 |
return (bytes(buf[:result[0]]),) + result[1:] |
| 3344 |
|
| 3345 |
|
| 3346 |
class SendrecvmsgDgramFlagsBase(SendrecvmsgBase): |
| 3347 |
# Defines flags to be checked in msg_flags for datagram sockets. |
| 3348 |
|
| 3349 |
@property |
| 3350 |
def msg_flags_non_eor_indicator(self): |
| 3351 |
return super().msg_flags_non_eor_indicator | socket.MSG_TRUNC |
| 3352 |
|
| 3353 |
|
| 3354 |
class SendrecvmsgSCTPFlagsBase(SendrecvmsgBase): |
| 3355 |
# Defines flags to be checked in msg_flags for SCTP sockets. |
| 3356 |
|
| 3357 |
@property |
| 3358 |
def msg_flags_eor_indicator(self): |
| 3359 |
return super().msg_flags_eor_indicator | socket.MSG_EOR |
| 3360 |
|
| 3361 |
|
| 3362 |
class SendrecvmsgConnectionlessBase(SendrecvmsgBase): |
| 3363 |
# Base class for tests on connectionless-mode sockets. Users must |
| 3364 |
# supply sockets on attributes cli and serv to be mapped to |
| 3365 |
# cli_sock and serv_sock respectively. |
| 3366 |
|
| 3367 |
@property |
| 3368 |
def serv_sock(self): |
| 3369 |
return self.serv |
| 3370 |
|
| 3371 |
@property |
| 3372 |
def cli_sock(self): |
| 3373 |
return self.cli |
| 3374 |
|
| 3375 |
@property |
| 3376 |
def sendmsg_to_server_defaults(self): |
| 3377 |
return ([], [], 0, self.serv_addr) |
| 3378 |
|
| 3379 |
def sendToServer(self, msg): |
| 3380 |
return self.cli_sock.sendto(msg, self.serv_addr) |
| 3381 |
|
| 3382 |
|
| 3383 |
class SendrecvmsgConnectedBase(SendrecvmsgBase): |
| 3384 |
# Base class for tests on connected sockets. Users must supply |
| 3385 |
# sockets on attributes serv_conn and cli_conn (representing the |
| 3386 |
# connections *to* the server and the client), to be mapped to |
| 3387 |
# cli_sock and serv_sock respectively. |
| 3388 |
|
| 3389 |
@property |
| 3390 |
def serv_sock(self): |
| 3391 |
return self.cli_conn |
| 3392 |
|
| 3393 |
@property |
| 3394 |
def cli_sock(self): |
| 3395 |
return self.serv_conn |
| 3396 |
|
| 3397 |
def checkRecvmsgAddress(self, addr1, addr2): |
| 3398 |
# Address is currently "unspecified" for a connected socket, |
| 3399 |
# so we don't examine it |
| 3400 |
pass |
| 3401 |
|
| 3402 |
|
| 3403 |
class SendrecvmsgServerTimeoutBase(SendrecvmsgBase): |
| 3404 |
# Base class to set a timeout on server's socket. |
| 3405 |
|
| 3406 |
def setUp(self): |
| 3407 |
super().setUp() |
| 3408 |
self.serv_sock.settimeout(self.fail_timeout) |
| 3409 |
|
| 3410 |
|
| 3411 |
class SendmsgTests(SendrecvmsgServerTimeoutBase): |
| 3412 |
# Tests for sendmsg() which can use any socket type and do not |
| 3413 |
# involve recvmsg() or recvmsg_into(). |
| 3414 |
|
| 3415 |
def testSendmsg(self): |
| 3416 |
# Send a simple message with sendmsg(). |
| 3417 |
self.assertEqual(self.serv_sock.recv(len(MSG)), MSG) |
| 3418 |
|
| 3419 |
def _testSendmsg(self): |
| 3420 |
self.assertEqual(self.sendmsgToServer([MSG]), len(MSG)) |
| 3421 |
|
| 3422 |
def testSendmsgDataGenerator(self): |
| 3423 |
# Send from buffer obtained from a generator (not a sequence). |
| 3424 |
self.assertEqual(self.serv_sock.recv(len(MSG)), MSG) |
| 3425 |
|
| 3426 |
def _testSendmsgDataGenerator(self): |
| 3427 |
self.assertEqual(self.sendmsgToServer((o for o in [MSG])), |
| 3428 |
len(MSG)) |
| 3429 |
|
| 3430 |
def testSendmsgAncillaryGenerator(self): |
| 3431 |
# Gather (empty) ancillary data from a generator. |
| 3432 |
self.assertEqual(self.serv_sock.recv(len(MSG)), MSG) |
| 3433 |
|
| 3434 |
def _testSendmsgAncillaryGenerator(self): |
| 3435 |
self.assertEqual(self.sendmsgToServer([MSG], (o for o in [])), |
| 3436 |
len(MSG)) |
| 3437 |
|
| 3438 |
def testSendmsgArray(self): |
| 3439 |
# Send data from an array instead of the usual bytes object. |
| 3440 |
self.assertEqual(self.serv_sock.recv(len(MSG)), MSG) |
| 3441 |
|
| 3442 |
def _testSendmsgArray(self): |
| 3443 |
self.assertEqual(self.sendmsgToServer([array.array("B", MSG)]), |
| 3444 |
len(MSG)) |
| 3445 |
|
| 3446 |
def testSendmsgGather(self): |
| 3447 |
# Send message data from more than one buffer (gather write). |
| 3448 |
self.assertEqual(self.serv_sock.recv(len(MSG)), MSG) |
| 3449 |
|
| 3450 |
def _testSendmsgGather(self): |
| 3451 |
self.assertEqual(self.sendmsgToServer([MSG[:3], MSG[3:]]), len(MSG)) |
| 3452 |
|
| 3453 |
def testSendmsgBadArgs(self): |
| 3454 |
# Check that sendmsg() rejects invalid arguments. |
| 3455 |
self.assertEqual(self.serv_sock.recv(1000), b"done") |
| 3456 |
|
| 3457 |
def _testSendmsgBadArgs(self): |
| 3458 |
self.assertRaises(TypeError, self.cli_sock.sendmsg) |
| 3459 |
self.assertRaises(TypeError, self.sendmsgToServer, |
| 3460 |
b"not in an iterable") |
| 3461 |
self.assertRaises(TypeError, self.sendmsgToServer, |
| 3462 |
object()) |
| 3463 |
self.assertRaises(TypeError, self.sendmsgToServer, |
| 3464 |
[object()]) |
| 3465 |
self.assertRaises(TypeError, self.sendmsgToServer, |
| 3466 |
[MSG, object()]) |
| 3467 |
self.assertRaises(TypeError, self.sendmsgToServer, |
| 3468 |
[MSG], object()) |
| 3469 |
self.assertRaises(TypeError, self.sendmsgToServer, |
| 3470 |
[MSG], [], object()) |
| 3471 |
self.assertRaises(TypeError, self.sendmsgToServer, |
| 3472 |
[MSG], [], 0, object()) |
| 3473 |
self.sendToServer(b"done") |
| 3474 |
|
| 3475 |
def testSendmsgBadCmsg(self): |
| 3476 |
# Check that invalid ancillary data items are rejected. |
| 3477 |
self.assertEqual(self.serv_sock.recv(1000), b"done") |
| 3478 |
|
| 3479 |
def _testSendmsgBadCmsg(self): |
| 3480 |
self.assertRaises(TypeError, self.sendmsgToServer, |
| 3481 |
[MSG], [object()]) |
| 3482 |
self.assertRaises(TypeError, self.sendmsgToServer, |
| 3483 |
[MSG], [(object(), 0, b"data")]) |
| 3484 |
self.assertRaises(TypeError, self.sendmsgToServer, |
| 3485 |
[MSG], [(0, object(), b"data")]) |
| 3486 |
self.assertRaises(TypeError, self.sendmsgToServer, |
| 3487 |
[MSG], [(0, 0, object())]) |
| 3488 |
self.assertRaises(TypeError, self.sendmsgToServer, |
| 3489 |
[MSG], [(0, 0)]) |
| 3490 |
self.assertRaises(TypeError, self.sendmsgToServer, |
| 3491 |
[MSG], [(0, 0, b"data", 42)]) |
| 3492 |
self.sendToServer(b"done") |
| 3493 |
|
| 3494 |
@requireAttrs(socket, "CMSG_SPACE") |
| 3495 |
def testSendmsgBadMultiCmsg(self): |
| 3496 |
# Check that invalid ancillary data items are rejected when |
| 3497 |
# more than one item is present. |
| 3498 |
self.assertEqual(self.serv_sock.recv(1000), b"done") |
| 3499 |
|
| 3500 |
@testSendmsgBadMultiCmsg.client_skip |
| 3501 |
def _testSendmsgBadMultiCmsg(self): |
| 3502 |
self.assertRaises(TypeError, self.sendmsgToServer, |
| 3503 |
[MSG], [0, 0, b""]) |
| 3504 |
self.assertRaises(TypeError, self.sendmsgToServer, |
| 3505 |
[MSG], [(0, 0, b""), object()]) |
| 3506 |
self.sendToServer(b"done") |
| 3507 |
|
| 3508 |
def testSendmsgExcessCmsgReject(self): |
| 3509 |
# Check that sendmsg() rejects excess ancillary data items |
| 3510 |
# when the number that can be sent is limited. |
| 3511 |
self.assertEqual(self.serv_sock.recv(1000), b"done") |
| 3512 |
|
| 3513 |
def _testSendmsgExcessCmsgReject(self): |
| 3514 |
if not hasattr(socket, "CMSG_SPACE"): |
| 3515 |
# Can only send one item |
| 3516 |
with self.assertRaises(OSError) as cm: |
| 3517 |
self.sendmsgToServer([MSG], [(0, 0, b""), (0, 0, b"")]) |
| 3518 |
self.assertIsNone(cm.exception.errno) |
| 3519 |
self.sendToServer(b"done") |
| 3520 |
|
| 3521 |
def testSendmsgAfterClose(self): |
| 3522 |
# Check that sendmsg() fails on a closed socket. |
| 3523 |
pass |
| 3524 |
|
| 3525 |
def _testSendmsgAfterClose(self): |
| 3526 |
self.cli_sock.close() |
| 3527 |
self.assertRaises(OSError, self.sendmsgToServer, [MSG]) |
| 3528 |
|
| 3529 |
|
| 3530 |
class SendmsgStreamTests(SendmsgTests): |
| 3531 |
# Tests for sendmsg() which require a stream socket and do not |
| 3532 |
# involve recvmsg() or recvmsg_into(). |
| 3533 |
|
| 3534 |
def testSendmsgExplicitNoneAddr(self): |
| 3535 |
# Check that peer address can be specified as None. |
| 3536 |
self.assertEqual(self.serv_sock.recv(len(MSG)), MSG) |
| 3537 |
|
| 3538 |
def _testSendmsgExplicitNoneAddr(self): |
| 3539 |
self.assertEqual(self.sendmsgToServer([MSG], [], 0, None), len(MSG)) |
| 3540 |
|
| 3541 |
def testSendmsgTimeout(self): |
| 3542 |
# Check that timeout works with sendmsg(). |
| 3543 |
self.assertEqual(self.serv_sock.recv(512), b"a"*512) |
| 3544 |
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
| 3545 |
|
| 3546 |
def _testSendmsgTimeout(self): |
| 3547 |
try: |
| 3548 |
self.cli_sock.settimeout(0.03) |
| 3549 |
try: |
| 3550 |
while True: |
| 3551 |
self.sendmsgToServer([b"a"*512]) |
| 3552 |
except TimeoutError: |
| 3553 |
pass |
| 3554 |
except OSError as exc: |
| 3555 |
if exc.errno != errno.ENOMEM: |
| 3556 |
raise |
| 3557 |
# bpo-33937 the test randomly fails on Travis CI with |
| 3558 |
# "OSError: [Errno 12] Cannot allocate memory" |
| 3559 |
else: |
| 3560 |
self.fail("TimeoutError not raised") |
| 3561 |
finally: |
| 3562 |
self.misc_event.set() |
| 3563 |
|
| 3564 |
# XXX: would be nice to have more tests for sendmsg flags argument. |
| 3565 |
|
| 3566 |
# Linux supports MSG_DONTWAIT when sending, but in general, it |
| 3567 |
# only works when receiving. Could add other platforms if they |
| 3568 |
# support it too. |
| 3569 |
@skipWithClientIf(sys.platform not in {"linux", "android"}, |
| 3570 |
"MSG_DONTWAIT not known to work on this platform when " |
| 3571 |
"sending") |
| 3572 |
def testSendmsgDontWait(self): |
| 3573 |
# Check that MSG_DONTWAIT in flags causes non-blocking behaviour. |
| 3574 |
self.assertEqual(self.serv_sock.recv(512), b"a"*512) |
| 3575 |
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
| 3576 |
|
| 3577 |
@testSendmsgDontWait.client_skip |
| 3578 |
def _testSendmsgDontWait(self): |
| 3579 |
try: |
| 3580 |
with self.assertRaises(OSError) as cm: |
| 3581 |
while True: |
| 3582 |
self.sendmsgToServer([b"a"*512], [], socket.MSG_DONTWAIT) |
| 3583 |
# bpo-33937: catch also ENOMEM, the test randomly fails on Travis CI |
| 3584 |
# with "OSError: [Errno 12] Cannot allocate memory" |
| 3585 |
self.assertIn(cm.exception.errno, |
| 3586 |
(errno.EAGAIN, errno.EWOULDBLOCK, errno.ENOMEM)) |
| 3587 |
finally: |
| 3588 |
self.misc_event.set() |
| 3589 |
|
| 3590 |
|
| 3591 |
class SendmsgConnectionlessTests(SendmsgTests): |
| 3592 |
# Tests for sendmsg() which require a connectionless-mode |
| 3593 |
# (e.g. datagram) socket, and do not involve recvmsg() or |
| 3594 |
# recvmsg_into(). |
| 3595 |
|
| 3596 |
def testSendmsgNoDestAddr(self): |
| 3597 |
# Check that sendmsg() fails when no destination address is |
| 3598 |
# given for unconnected socket. |
| 3599 |
pass |
| 3600 |
|
| 3601 |
def _testSendmsgNoDestAddr(self): |
| 3602 |
self.assertRaises(OSError, self.cli_sock.sendmsg, |
| 3603 |
[MSG]) |
| 3604 |
self.assertRaises(OSError, self.cli_sock.sendmsg, |
| 3605 |
[MSG], [], 0, None) |
| 3606 |
|
| 3607 |
|
| 3608 |
class RecvmsgGenericTests(SendrecvmsgBase): |
| 3609 |
# Tests for recvmsg() which can also be emulated using |
| 3610 |
# recvmsg_into(), and can use any socket type. |
| 3611 |
|
| 3612 |
def testRecvmsg(self): |
| 3613 |
# Receive a simple message with recvmsg[_into](). |
| 3614 |
msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, len(MSG)) |
| 3615 |
self.assertEqual(msg, MSG) |
| 3616 |
self.checkRecvmsgAddress(addr, self.cli_addr) |
| 3617 |
self.assertEqual(ancdata, []) |
| 3618 |
self.checkFlags(flags, eor=True) |
| 3619 |
|
| 3620 |
def _testRecvmsg(self): |
| 3621 |
self.sendToServer(MSG) |
| 3622 |
|
| 3623 |
def testRecvmsgExplicitDefaults(self): |
| 3624 |
# Test recvmsg[_into]() with default arguments provided explicitly. |
| 3625 |
msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, |
| 3626 |
len(MSG), 0, 0) |
| 3627 |
self.assertEqual(msg, MSG) |
| 3628 |
self.checkRecvmsgAddress(addr, self.cli_addr) |
| 3629 |
self.assertEqual(ancdata, []) |
| 3630 |
self.checkFlags(flags, eor=True) |
| 3631 |
|
| 3632 |
def _testRecvmsgExplicitDefaults(self): |
| 3633 |
self.sendToServer(MSG) |
| 3634 |
|
| 3635 |
def testRecvmsgShorter(self): |
| 3636 |
# Receive a message smaller than buffer. |
| 3637 |
msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, |
| 3638 |
len(MSG) + 42) |
| 3639 |
self.assertEqual(msg, MSG) |
| 3640 |
self.checkRecvmsgAddress(addr, self.cli_addr) |
| 3641 |
self.assertEqual(ancdata, []) |
| 3642 |
self.checkFlags(flags, eor=True) |
| 3643 |
|
| 3644 |
def _testRecvmsgShorter(self): |
| 3645 |
self.sendToServer(MSG) |
| 3646 |
|
| 3647 |
def testRecvmsgTrunc(self): |
| 3648 |
# Receive part of message, check for truncation indicators. |
| 3649 |
msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, |
| 3650 |
len(MSG) - 3) |
| 3651 |
self.assertEqual(msg, MSG[:-3]) |
| 3652 |
self.checkRecvmsgAddress(addr, self.cli_addr) |
| 3653 |
self.assertEqual(ancdata, []) |
| 3654 |
self.checkFlags(flags, eor=False) |
| 3655 |
|
| 3656 |
def _testRecvmsgTrunc(self): |
| 3657 |
self.sendToServer(MSG) |
| 3658 |
|
| 3659 |
def testRecvmsgShortAncillaryBuf(self): |
| 3660 |
# Test ancillary data buffer too small to hold any ancillary data. |
| 3661 |
msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, |
| 3662 |
len(MSG), 1) |
| 3663 |
self.assertEqual(msg, MSG) |
| 3664 |
self.checkRecvmsgAddress(addr, self.cli_addr) |
| 3665 |
self.assertEqual(ancdata, []) |
| 3666 |
self.checkFlags(flags, eor=True) |
| 3667 |
|
| 3668 |
def _testRecvmsgShortAncillaryBuf(self): |
| 3669 |
self.sendToServer(MSG) |
| 3670 |
|
| 3671 |
def testRecvmsgLongAncillaryBuf(self): |
| 3672 |
# Test large ancillary data buffer. |
| 3673 |
msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, |
| 3674 |
len(MSG), 10240) |
| 3675 |
self.assertEqual(msg, MSG) |
| 3676 |
self.checkRecvmsgAddress(addr, self.cli_addr) |
| 3677 |
self.assertEqual(ancdata, []) |
| 3678 |
self.checkFlags(flags, eor=True) |
| 3679 |
|
| 3680 |
def _testRecvmsgLongAncillaryBuf(self): |
| 3681 |
self.sendToServer(MSG) |
| 3682 |
|
| 3683 |
def testRecvmsgAfterClose(self): |
| 3684 |
# Check that recvmsg[_into]() fails on a closed socket. |
| 3685 |
self.serv_sock.close() |
| 3686 |
self.assertRaises(OSError, self.doRecvmsg, self.serv_sock, 1024) |
| 3687 |
|
| 3688 |
def _testRecvmsgAfterClose(self): |
| 3689 |
pass |
| 3690 |
|
| 3691 |
def testRecvmsgTimeout(self): |
| 3692 |
# Check that timeout works. |
| 3693 |
try: |
| 3694 |
self.serv_sock.settimeout(0.03) |
| 3695 |
self.assertRaises(TimeoutError, |
| 3696 |
self.doRecvmsg, self.serv_sock, len(MSG)) |
| 3697 |
finally: |
| 3698 |
self.misc_event.set() |
| 3699 |
|
| 3700 |
def _testRecvmsgTimeout(self): |
| 3701 |
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
| 3702 |
|
| 3703 |
@requireAttrs(socket, "MSG_PEEK") |
| 3704 |
def testRecvmsgPeek(self): |
| 3705 |
# Check that MSG_PEEK in flags enables examination of pending |
| 3706 |
# data without consuming it. |
| 3707 |
|
| 3708 |
# Receive part of data with MSG_PEEK. |
| 3709 |
msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, |
| 3710 |
len(MSG) - 3, 0, |
| 3711 |
socket.MSG_PEEK) |
| 3712 |
self.assertEqual(msg, MSG[:-3]) |
| 3713 |
self.checkRecvmsgAddress(addr, self.cli_addr) |
| 3714 |
self.assertEqual(ancdata, []) |
| 3715 |
# Ignoring MSG_TRUNC here (so this test is the same for stream |
| 3716 |
# and datagram sockets). Some wording in POSIX seems to |
| 3717 |
# suggest that it needn't be set when peeking, but that may |
| 3718 |
# just be a slip. |
| 3719 |
self.checkFlags(flags, eor=False, |
| 3720 |
ignore=getattr(socket, "MSG_TRUNC", 0)) |
| 3721 |
|
| 3722 |
# Receive all data with MSG_PEEK. |
| 3723 |
msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, |
| 3724 |
len(MSG), 0, |
| 3725 |
socket.MSG_PEEK) |
| 3726 |
self.assertEqual(msg, MSG) |
| 3727 |
self.checkRecvmsgAddress(addr, self.cli_addr) |
| 3728 |
self.assertEqual(ancdata, []) |
| 3729 |
self.checkFlags(flags, eor=True) |
| 3730 |
|
| 3731 |
# Check that the same data can still be received normally. |
| 3732 |
msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, len(MSG)) |
| 3733 |
self.assertEqual(msg, MSG) |
| 3734 |
self.checkRecvmsgAddress(addr, self.cli_addr) |
| 3735 |
self.assertEqual(ancdata, []) |
| 3736 |
self.checkFlags(flags, eor=True) |
| 3737 |
|
| 3738 |
@testRecvmsgPeek.client_skip |
| 3739 |
def _testRecvmsgPeek(self): |
| 3740 |
self.sendToServer(MSG) |
| 3741 |
|
| 3742 |
@requireAttrs(socket.socket, "sendmsg") |
| 3743 |
def testRecvmsgFromSendmsg(self): |
| 3744 |
# Test receiving with recvmsg[_into]() when message is sent |
| 3745 |
# using sendmsg(). |
| 3746 |
self.serv_sock.settimeout(self.fail_timeout) |
| 3747 |
msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, len(MSG)) |
| 3748 |
self.assertEqual(msg, MSG) |
| 3749 |
self.checkRecvmsgAddress(addr, self.cli_addr) |
| 3750 |
self.assertEqual(ancdata, []) |
| 3751 |
self.checkFlags(flags, eor=True) |
| 3752 |
|
| 3753 |
@testRecvmsgFromSendmsg.client_skip |
| 3754 |
def _testRecvmsgFromSendmsg(self): |
| 3755 |
self.assertEqual(self.sendmsgToServer([MSG[:3], MSG[3:]]), len(MSG)) |
| 3756 |
|
| 3757 |
|
| 3758 |
class RecvmsgGenericStreamTests(RecvmsgGenericTests): |
| 3759 |
# Tests which require a stream socket and can use either recvmsg() |
| 3760 |
# or recvmsg_into(). |
| 3761 |
|
| 3762 |
def testRecvmsgEOF(self): |
| 3763 |
# Receive end-of-stream indicator (b"", peer socket closed). |
| 3764 |
msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, 1024) |
| 3765 |
self.assertEqual(msg, b"") |
| 3766 |
self.checkRecvmsgAddress(addr, self.cli_addr) |
| 3767 |
self.assertEqual(ancdata, []) |
| 3768 |
self.checkFlags(flags, eor=None) # Might not have end-of-record marker |
| 3769 |
|
| 3770 |
def _testRecvmsgEOF(self): |
| 3771 |
self.cli_sock.close() |
| 3772 |
|
| 3773 |
def testRecvmsgOverflow(self): |
| 3774 |
# Receive a message in more than one chunk. |
| 3775 |
seg1, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, |
| 3776 |
len(MSG) - 3) |
| 3777 |
self.checkRecvmsgAddress(addr, self.cli_addr) |
| 3778 |
self.assertEqual(ancdata, []) |
| 3779 |
self.checkFlags(flags, eor=False) |
| 3780 |
|
| 3781 |
seg2, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, 1024) |
| 3782 |
self.checkRecvmsgAddress(addr, self.cli_addr) |
| 3783 |
self.assertEqual(ancdata, []) |
| 3784 |
self.checkFlags(flags, eor=True) |
| 3785 |
|
| 3786 |
msg = seg1 + seg2 |
| 3787 |
self.assertEqual(msg, MSG) |
| 3788 |
|
| 3789 |
def _testRecvmsgOverflow(self): |
| 3790 |
self.sendToServer(MSG) |
| 3791 |
|
| 3792 |
|
| 3793 |
class RecvmsgTests(RecvmsgGenericTests): |
| 3794 |
# Tests for recvmsg() which can use any socket type. |
| 3795 |
|
| 3796 |
def testRecvmsgBadArgs(self): |
| 3797 |
# Check that recvmsg() rejects invalid arguments. |
| 3798 |
self.assertRaises(TypeError, self.serv_sock.recvmsg) |
| 3799 |
self.assertRaises(ValueError, self.serv_sock.recvmsg, |
| 3800 |
-1, 0, 0) |
| 3801 |
self.assertRaises(ValueError, self.serv_sock.recvmsg, |
| 3802 |
len(MSG), -1, 0) |
| 3803 |
self.assertRaises(TypeError, self.serv_sock.recvmsg, |
| 3804 |
[bytearray(10)], 0, 0) |
| 3805 |
self.assertRaises(TypeError, self.serv_sock.recvmsg, |
| 3806 |
object(), 0, 0) |
| 3807 |
self.assertRaises(TypeError, self.serv_sock.recvmsg, |
| 3808 |
len(MSG), object(), 0) |
| 3809 |
self.assertRaises(TypeError, self.serv_sock.recvmsg, |
| 3810 |
len(MSG), 0, object()) |
| 3811 |
|
| 3812 |
msg, ancdata, flags, addr = self.serv_sock.recvmsg(len(MSG), 0, 0) |
| 3813 |
self.assertEqual(msg, MSG) |
| 3814 |
self.checkRecvmsgAddress(addr, self.cli_addr) |
| 3815 |
self.assertEqual(ancdata, []) |
| 3816 |
self.checkFlags(flags, eor=True) |
| 3817 |
|
| 3818 |
def _testRecvmsgBadArgs(self): |
| 3819 |
self.sendToServer(MSG) |
| 3820 |
|
| 3821 |
|
| 3822 |
class RecvmsgIntoTests(RecvmsgIntoMixin, RecvmsgGenericTests): |
| 3823 |
# Tests for recvmsg_into() which can use any socket type. |
| 3824 |
|
| 3825 |
def testRecvmsgIntoBadArgs(self): |
| 3826 |
# Check that recvmsg_into() rejects invalid arguments. |
| 3827 |
buf = bytearray(len(MSG)) |
| 3828 |
self.assertRaises(TypeError, self.serv_sock.recvmsg_into) |
| 3829 |
self.assertRaises(TypeError, self.serv_sock.recvmsg_into, |
| 3830 |
len(MSG), 0, 0) |
| 3831 |
self.assertRaises(TypeError, self.serv_sock.recvmsg_into, |
| 3832 |
buf, 0, 0) |
| 3833 |
self.assertRaises(TypeError, self.serv_sock.recvmsg_into, |
| 3834 |
[object()], 0, 0) |
| 3835 |
self.assertRaises(TypeError, self.serv_sock.recvmsg_into, |
| 3836 |
[b"I'm not writable"], 0, 0) |
| 3837 |
self.assertRaises(TypeError, self.serv_sock.recvmsg_into, |
| 3838 |
[buf, object()], 0, 0) |
| 3839 |
self.assertRaises(ValueError, self.serv_sock.recvmsg_into, |
| 3840 |
[buf], -1, 0) |
| 3841 |
self.assertRaises(TypeError, self.serv_sock.recvmsg_into, |
| 3842 |
[buf], object(), 0) |
| 3843 |
self.assertRaises(TypeError, self.serv_sock.recvmsg_into, |
| 3844 |
[buf], 0, object()) |
| 3845 |
|
| 3846 |
nbytes, ancdata, flags, addr = self.serv_sock.recvmsg_into([buf], 0, 0) |
| 3847 |
self.assertEqual(nbytes, len(MSG)) |
| 3848 |
self.assertEqual(buf, bytearray(MSG)) |
| 3849 |
self.checkRecvmsgAddress(addr, self.cli_addr) |
| 3850 |
self.assertEqual(ancdata, []) |
| 3851 |
self.checkFlags(flags, eor=True) |
| 3852 |
|
| 3853 |
def _testRecvmsgIntoBadArgs(self): |
| 3854 |
self.sendToServer(MSG) |
| 3855 |
|
| 3856 |
def testRecvmsgIntoGenerator(self): |
| 3857 |
# Receive into buffer obtained from a generator (not a sequence). |
| 3858 |
buf = bytearray(len(MSG)) |
| 3859 |
nbytes, ancdata, flags, addr = self.serv_sock.recvmsg_into( |
| 3860 |
(o for o in [buf])) |
| 3861 |
self.assertEqual(nbytes, len(MSG)) |
| 3862 |
self.assertEqual(buf, bytearray(MSG)) |
| 3863 |
self.checkRecvmsgAddress(addr, self.cli_addr) |
| 3864 |
self.assertEqual(ancdata, []) |
| 3865 |
self.checkFlags(flags, eor=True) |
| 3866 |
|
| 3867 |
def _testRecvmsgIntoGenerator(self): |
| 3868 |
self.sendToServer(MSG) |
| 3869 |
|
| 3870 |
def testRecvmsgIntoArray(self): |
| 3871 |
# Receive into an array rather than the usual bytearray. |
| 3872 |
buf = array.array("B", [0] * len(MSG)) |
| 3873 |
nbytes, ancdata, flags, addr = self.serv_sock.recvmsg_into([buf]) |
| 3874 |
self.assertEqual(nbytes, len(MSG)) |
| 3875 |
self.assertEqual(buf.tobytes(), MSG) |
| 3876 |
self.checkRecvmsgAddress(addr, self.cli_addr) |
| 3877 |
self.assertEqual(ancdata, []) |
| 3878 |
self.checkFlags(flags, eor=True) |
| 3879 |
|
| 3880 |
def _testRecvmsgIntoArray(self): |
| 3881 |
self.sendToServer(MSG) |
| 3882 |
|
| 3883 |
def testRecvmsgIntoScatter(self): |
| 3884 |
# Receive into multiple buffers (scatter write). |
| 3885 |
b1 = bytearray(b"----") |
| 3886 |
b2 = bytearray(b"0123456789") |
| 3887 |
b3 = bytearray(b"--------------") |
| 3888 |
nbytes, ancdata, flags, addr = self.serv_sock.recvmsg_into( |
| 3889 |
[b1, memoryview(b2)[2:9], b3]) |
| 3890 |
self.assertEqual(nbytes, len(b"Mary had a little lamb")) |
| 3891 |
self.assertEqual(b1, bytearray(b"Mary")) |
| 3892 |
self.assertEqual(b2, bytearray(b"01 had a 9")) |
| 3893 |
self.assertEqual(b3, bytearray(b"little lamb---")) |
| 3894 |
self.checkRecvmsgAddress(addr, self.cli_addr) |
| 3895 |
self.assertEqual(ancdata, []) |
| 3896 |
self.checkFlags(flags, eor=True) |
| 3897 |
|
| 3898 |
def _testRecvmsgIntoScatter(self): |
| 3899 |
self.sendToServer(b"Mary had a little lamb") |
| 3900 |
|
| 3901 |
|
| 3902 |
class CmsgMacroTests(unittest.TestCase): |
| 3903 |
# Test the functions CMSG_LEN() and CMSG_SPACE(). Tests |
| 3904 |
# assumptions used by sendmsg() and recvmsg[_into](), which share |
| 3905 |
# code with these functions. |
| 3906 |
|
| 3907 |
# Match the definition in socketmodule.c |
| 3908 |
try: |
| 3909 |
import _testcapi |
| 3910 |
except ImportError: |
| 3911 |
socklen_t_limit = 0x7fffffff |
| 3912 |
else: |
| 3913 |
socklen_t_limit = min(0x7fffffff, _testcapi.INT_MAX) |
| 3914 |
|
| 3915 |
@requireAttrs(socket, "CMSG_LEN") |
| 3916 |
def testCMSG_LEN(self): |
| 3917 |
# Test CMSG_LEN() with various valid and invalid values, |
| 3918 |
# checking the assumptions used by recvmsg() and sendmsg(). |
| 3919 |
toobig = self.socklen_t_limit - socket.CMSG_LEN(0) + 1 |
| 3920 |
values = list(range(257)) + list(range(toobig - 257, toobig)) |
| 3921 |
|
| 3922 |
# struct cmsghdr has at least three members, two of which are ints |
| 3923 |
self.assertGreater(socket.CMSG_LEN(0), array.array("i").itemsize * 2) |
| 3924 |
for n in values: |
| 3925 |
ret = socket.CMSG_LEN(n) |
| 3926 |
# This is how recvmsg() calculates the data size |
| 3927 |
self.assertEqual(ret - socket.CMSG_LEN(0), n) |
| 3928 |
self.assertLessEqual(ret, self.socklen_t_limit) |
| 3929 |
|
| 3930 |
self.assertRaises(OverflowError, socket.CMSG_LEN, -1) |
| 3931 |
# sendmsg() shares code with these functions, and requires |
| 3932 |
# that it reject values over the limit. |
| 3933 |
self.assertRaises(OverflowError, socket.CMSG_LEN, toobig) |
| 3934 |
self.assertRaises(OverflowError, socket.CMSG_LEN, sys.maxsize) |
| 3935 |
|
| 3936 |
@requireAttrs(socket, "CMSG_SPACE") |
| 3937 |
def testCMSG_SPACE(self): |
| 3938 |
# Test CMSG_SPACE() with various valid and invalid values, |
| 3939 |
# checking the assumptions used by sendmsg(). |
| 3940 |
toobig = self.socklen_t_limit - socket.CMSG_SPACE(1) + 1 |
| 3941 |
if SOLARIS and platform.processor() == "sparc": |
| 3942 |
# On Solaris SPARC, number of bytes returned by socket.CMSG_SPACE |
| 3943 |
# increases at different lengths; see gh-91214. |
| 3944 |
toobig -= 3 |
| 3945 |
values = list(range(257)) + list(range(toobig - 257, toobig)) |
| 3946 |
|
| 3947 |
last = socket.CMSG_SPACE(0) |
| 3948 |
# struct cmsghdr has at least three members, two of which are ints |
| 3949 |
self.assertGreater(last, array.array("i").itemsize * 2) |
| 3950 |
for n in values: |
| 3951 |
ret = socket.CMSG_SPACE(n) |
| 3952 |
self.assertGreaterEqual(ret, last) |
| 3953 |
self.assertGreaterEqual(ret, socket.CMSG_LEN(n)) |
| 3954 |
self.assertGreaterEqual(ret, n + socket.CMSG_LEN(0)) |
| 3955 |
self.assertLessEqual(ret, self.socklen_t_limit) |
| 3956 |
last = ret |
| 3957 |
|
| 3958 |
self.assertRaises(OverflowError, socket.CMSG_SPACE, -1) |
| 3959 |
# sendmsg() shares code with these functions, and requires |
| 3960 |
# that it reject values over the limit. |
| 3961 |
self.assertRaises(OverflowError, socket.CMSG_SPACE, toobig) |
| 3962 |
self.assertRaises(OverflowError, socket.CMSG_SPACE, sys.maxsize) |
| 3963 |
|
| 3964 |
|
| 3965 |
class SCMRightsTest(SendrecvmsgServerTimeoutBase): |
| 3966 |
# Tests for file descriptor passing on Unix-domain sockets. |
| 3967 |
|
| 3968 |
# Invalid file descriptor value that's unlikely to evaluate to a |
| 3969 |
# real FD even if one of its bytes is replaced with a different |
| 3970 |
# value (which shouldn't actually happen). |
| 3971 |
badfd = -0x5555 |
| 3972 |
|
| 3973 |
def newFDs(self, n): |
| 3974 |
# Return a list of n file descriptors for newly-created files |
| 3975 |
# containing their list indices as ASCII numbers. |
| 3976 |
fds = [] |
| 3977 |
for i in range(n): |
| 3978 |
fd, path = tempfile.mkstemp() |
| 3979 |
self.addCleanup(os.unlink, path) |
| 3980 |
self.addCleanup(os.close, fd) |
| 3981 |
os.write(fd, str(i).encode()) |
| 3982 |
fds.append(fd) |
| 3983 |
return fds |
| 3984 |
|
| 3985 |
def checkFDs(self, fds): |
| 3986 |
# Check that the file descriptors in the given list contain |
| 3987 |
# their correct list indices as ASCII numbers. |
| 3988 |
for n, fd in enumerate(fds): |
| 3989 |
os.lseek(fd, 0, os.SEEK_SET) |
| 3990 |
self.assertEqual(os.read(fd, 1024), str(n).encode()) |
| 3991 |
|
| 3992 |
def registerRecvmsgResult(self, result): |
| 3993 |
self.addCleanup(self.closeRecvmsgFDs, result) |
| 3994 |
|
| 3995 |
def closeRecvmsgFDs(self, recvmsg_result): |
| 3996 |
# Close all file descriptors specified in the ancillary data |
| 3997 |
# of the given return value from recvmsg() or recvmsg_into(). |
| 3998 |
for cmsg_level, cmsg_type, cmsg_data in recvmsg_result[1]: |
| 3999 |
if (cmsg_level == socket.SOL_SOCKET and |
| 4000 |
cmsg_type == socket.SCM_RIGHTS): |
| 4001 |
fds = array.array("i") |
| 4002 |
fds.frombytes(cmsg_data[: |
| 4003 |
len(cmsg_data) - (len(cmsg_data) % fds.itemsize)]) |
| 4004 |
for fd in fds: |
| 4005 |
os.close(fd) |
| 4006 |
|
| 4007 |
def createAndSendFDs(self, n): |
| 4008 |
# Send n new file descriptors created by newFDs() to the |
| 4009 |
# server, with the constant MSG as the non-ancillary data. |
| 4010 |
self.assertEqual( |
| 4011 |
self.sendmsgToServer([MSG], |
| 4012 |
[(socket.SOL_SOCKET, |
| 4013 |
socket.SCM_RIGHTS, |
| 4014 |
array.array("i", self.newFDs(n)))]), |
| 4015 |
len(MSG)) |
| 4016 |
|
| 4017 |
def checkRecvmsgFDs(self, numfds, result, maxcmsgs=1, ignoreflags=0): |
| 4018 |
# Check that constant MSG was received with numfds file |
| 4019 |
# descriptors in a maximum of maxcmsgs control messages (which |
| 4020 |
# must contain only complete integers). By default, check |
| 4021 |
# that MSG_CTRUNC is unset, but ignore any flags in |
| 4022 |
# ignoreflags. |
| 4023 |
msg, ancdata, flags, addr = result |
| 4024 |
self.assertEqual(msg, MSG) |
| 4025 |
self.checkRecvmsgAddress(addr, self.cli_addr) |
| 4026 |
self.checkFlags(flags, eor=True, checkunset=socket.MSG_CTRUNC, |
| 4027 |
ignore=ignoreflags) |
| 4028 |
|
| 4029 |
self.assertIsInstance(ancdata, list) |
| 4030 |
self.assertLessEqual(len(ancdata), maxcmsgs) |
| 4031 |
fds = array.array("i") |
| 4032 |
for item in ancdata: |
| 4033 |
self.assertIsInstance(item, tuple) |
| 4034 |
cmsg_level, cmsg_type, cmsg_data = item |
| 4035 |
self.assertEqual(cmsg_level, socket.SOL_SOCKET) |
| 4036 |
self.assertEqual(cmsg_type, socket.SCM_RIGHTS) |
| 4037 |
self.assertIsInstance(cmsg_data, bytes) |
| 4038 |
self.assertEqual(len(cmsg_data) % SIZEOF_INT, 0) |
| 4039 |
fds.frombytes(cmsg_data) |
| 4040 |
|
| 4041 |
self.assertEqual(len(fds), numfds) |
| 4042 |
self.checkFDs(fds) |
| 4043 |
|
| 4044 |
def testFDPassSimple(self): |
| 4045 |
# Pass a single FD (array read from bytes object). |
| 4046 |
self.checkRecvmsgFDs(1, self.doRecvmsg(self.serv_sock, |
| 4047 |
len(MSG), 10240)) |
| 4048 |
|
| 4049 |
def _testFDPassSimple(self): |
| 4050 |
self.assertEqual( |
| 4051 |
self.sendmsgToServer( |
| 4052 |
[MSG], |
| 4053 |
[(socket.SOL_SOCKET, |
| 4054 |
socket.SCM_RIGHTS, |
| 4055 |
array.array("i", self.newFDs(1)).tobytes())]), |
| 4056 |
len(MSG)) |
| 4057 |
|
| 4058 |
def testMultipleFDPass(self): |
| 4059 |
# Pass multiple FDs in a single array. |
| 4060 |
self.checkRecvmsgFDs(4, self.doRecvmsg(self.serv_sock, |
| 4061 |
len(MSG), 10240)) |
| 4062 |
|
| 4063 |
def _testMultipleFDPass(self): |
| 4064 |
self.createAndSendFDs(4) |
| 4065 |
|
| 4066 |
@requireAttrs(socket, "CMSG_SPACE") |
| 4067 |
def testFDPassCMSG_SPACE(self): |
| 4068 |
# Test using CMSG_SPACE() to calculate ancillary buffer size. |
| 4069 |
self.checkRecvmsgFDs( |
| 4070 |
4, self.doRecvmsg(self.serv_sock, len(MSG), |
| 4071 |
socket.CMSG_SPACE(4 * SIZEOF_INT))) |
| 4072 |
|
| 4073 |
@testFDPassCMSG_SPACE.client_skip |
| 4074 |
def _testFDPassCMSG_SPACE(self): |
| 4075 |
self.createAndSendFDs(4) |
| 4076 |
|
| 4077 |
def testFDPassCMSG_LEN(self): |
| 4078 |
# Test using CMSG_LEN() to calculate ancillary buffer size. |
| 4079 |
self.checkRecvmsgFDs(1, |
| 4080 |
self.doRecvmsg(self.serv_sock, len(MSG), |
| 4081 |
socket.CMSG_LEN(4 * SIZEOF_INT)), |
| 4082 |
# RFC 3542 says implementations may set |
| 4083 |
# MSG_CTRUNC if there isn't enough space |
| 4084 |
# for trailing padding. |
| 4085 |
ignoreflags=socket.MSG_CTRUNC) |
| 4086 |
|
| 4087 |
def _testFDPassCMSG_LEN(self): |
| 4088 |
self.createAndSendFDs(1) |
| 4089 |
|
| 4090 |
@unittest.skipIf(is_apple, "skipping, see issue #12958") |
| 4091 |
@unittest.skipIf(SOLARIS, "skipping, see gh-91214") |
| 4092 |
@unittest.skipIf(AIX, "skipping, see issue #22397") |
| 4093 |
@requireAttrs(socket, "CMSG_SPACE") |
| 4094 |
def testFDPassSeparate(self): |
| 4095 |
# Pass two FDs in two separate arrays. Arrays may be combined |
| 4096 |
# into a single control message by the OS. |
| 4097 |
self.checkRecvmsgFDs(2, |
| 4098 |
self.doRecvmsg(self.serv_sock, len(MSG), 10240), |
| 4099 |
maxcmsgs=2) |
| 4100 |
|
| 4101 |
@testFDPassSeparate.client_skip |
| 4102 |
@unittest.skipIf(is_apple, "skipping, see issue #12958") |
| 4103 |
@unittest.skipIf(SOLARIS, "skipping, see gh-91214") |
| 4104 |
@unittest.skipIf(AIX, "skipping, see issue #22397") |
| 4105 |
def _testFDPassSeparate(self): |
| 4106 |
fd0, fd1 = self.newFDs(2) |
| 4107 |
self.assertEqual( |
| 4108 |
self.sendmsgToServer([MSG], [(socket.SOL_SOCKET, |
| 4109 |
socket.SCM_RIGHTS, |
| 4110 |
array.array("i", [fd0])), |
| 4111 |
(socket.SOL_SOCKET, |
| 4112 |
socket.SCM_RIGHTS, |
| 4113 |
array.array("i", [fd1]))]), |
| 4114 |
len(MSG)) |
| 4115 |
|
| 4116 |
@unittest.skipIf(is_apple, "skipping, see issue #12958") |
| 4117 |
@unittest.skipIf(SOLARIS, "skipping, see gh-91214") |
| 4118 |
@unittest.skipIf(AIX, "skipping, see issue #22397") |
| 4119 |
@requireAttrs(socket, "CMSG_SPACE") |
| 4120 |
def testFDPassSeparateMinSpace(self): |
| 4121 |
# Pass two FDs in two separate arrays, receiving them into the |
| 4122 |
# minimum space for two arrays. |
| 4123 |
num_fds = 2 |
| 4124 |
self.checkRecvmsgFDs(num_fds, |
| 4125 |
self.doRecvmsg(self.serv_sock, len(MSG), |
| 4126 |
socket.CMSG_SPACE(SIZEOF_INT) + |
| 4127 |
socket.CMSG_LEN(SIZEOF_INT * num_fds)), |
| 4128 |
maxcmsgs=2, ignoreflags=socket.MSG_CTRUNC) |
| 4129 |
|
| 4130 |
@testFDPassSeparateMinSpace.client_skip |
| 4131 |
@unittest.skipIf(is_apple, "skipping, see issue #12958") |
| 4132 |
@unittest.skipIf(SOLARIS, "skipping, see gh-91214") |
| 4133 |
@unittest.skipIf(AIX, "skipping, see issue #22397") |
| 4134 |
def _testFDPassSeparateMinSpace(self): |
| 4135 |
fd0, fd1 = self.newFDs(2) |
| 4136 |
self.assertEqual( |
| 4137 |
self.sendmsgToServer([MSG], [(socket.SOL_SOCKET, |
| 4138 |
socket.SCM_RIGHTS, |
| 4139 |
array.array("i", [fd0])), |
| 4140 |
(socket.SOL_SOCKET, |
| 4141 |
socket.SCM_RIGHTS, |
| 4142 |
array.array("i", [fd1]))]), |
| 4143 |
len(MSG)) |
| 4144 |
|
| 4145 |
def sendAncillaryIfPossible(self, msg, ancdata): |
| 4146 |
# Try to send msg and ancdata to server, but if the system |
| 4147 |
# call fails, just send msg with no ancillary data. |
| 4148 |
try: |
| 4149 |
nbytes = self.sendmsgToServer([msg], ancdata) |
| 4150 |
except OSError as e: |
| 4151 |
# Check that it was the system call that failed |
| 4152 |
self.assertIsInstance(e.errno, int) |
| 4153 |
nbytes = self.sendmsgToServer([msg]) |
| 4154 |
self.assertEqual(nbytes, len(msg)) |
| 4155 |
|
| 4156 |
@unittest.skipIf(is_apple, "skipping, see issue #12958") |
| 4157 |
def testFDPassEmpty(self): |
| 4158 |
# Try to pass an empty FD array. Can receive either no array |
| 4159 |
# or an empty array. |
| 4160 |
self.checkRecvmsgFDs(0, self.doRecvmsg(self.serv_sock, |
| 4161 |
len(MSG), 10240), |
| 4162 |
ignoreflags=socket.MSG_CTRUNC) |
| 4163 |
|
| 4164 |
def _testFDPassEmpty(self): |
| 4165 |
self.sendAncillaryIfPossible(MSG, [(socket.SOL_SOCKET, |
| 4166 |
socket.SCM_RIGHTS, |
| 4167 |
b"")]) |
| 4168 |
|
| 4169 |
def testFDPassPartialInt(self): |
| 4170 |
# Try to pass a truncated FD array. |
| 4171 |
msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, |
| 4172 |
len(MSG), 10240) |
| 4173 |
self.assertEqual(msg, MSG) |
| 4174 |
self.checkRecvmsgAddress(addr, self.cli_addr) |
| 4175 |
self.checkFlags(flags, eor=True, ignore=socket.MSG_CTRUNC) |
| 4176 |
self.assertLessEqual(len(ancdata), 1) |
| 4177 |
for cmsg_level, cmsg_type, cmsg_data in ancdata: |
| 4178 |
self.assertEqual(cmsg_level, socket.SOL_SOCKET) |
| 4179 |
self.assertEqual(cmsg_type, socket.SCM_RIGHTS) |
| 4180 |
self.assertLess(len(cmsg_data), SIZEOF_INT) |
| 4181 |
|
| 4182 |
def _testFDPassPartialInt(self): |
| 4183 |
self.sendAncillaryIfPossible( |
| 4184 |
MSG, |
| 4185 |
[(socket.SOL_SOCKET, |
| 4186 |
socket.SCM_RIGHTS, |
| 4187 |
array.array("i", [self.badfd]).tobytes()[:-1])]) |
| 4188 |
|
| 4189 |
@requireAttrs(socket, "CMSG_SPACE") |
| 4190 |
def testFDPassPartialIntInMiddle(self): |
| 4191 |
# Try to pass two FD arrays, the first of which is truncated. |
| 4192 |
msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, |
| 4193 |
len(MSG), 10240) |
| 4194 |
self.assertEqual(msg, MSG) |
| 4195 |
self.checkRecvmsgAddress(addr, self.cli_addr) |
| 4196 |
self.checkFlags(flags, eor=True, ignore=socket.MSG_CTRUNC) |
| 4197 |
self.assertLessEqual(len(ancdata), 2) |
| 4198 |
fds = array.array("i") |
| 4199 |
# Arrays may have been combined in a single control message |
| 4200 |
for cmsg_level, cmsg_type, cmsg_data in ancdata: |
| 4201 |
self.assertEqual(cmsg_level, socket.SOL_SOCKET) |
| 4202 |
self.assertEqual(cmsg_type, socket.SCM_RIGHTS) |
| 4203 |
fds.frombytes(cmsg_data[: |
| 4204 |
len(cmsg_data) - (len(cmsg_data) % fds.itemsize)]) |
| 4205 |
self.assertLessEqual(len(fds), 2) |
| 4206 |
self.checkFDs(fds) |
| 4207 |
|
| 4208 |
@testFDPassPartialIntInMiddle.client_skip |
| 4209 |
def _testFDPassPartialIntInMiddle(self): |
| 4210 |
fd0, fd1 = self.newFDs(2) |
| 4211 |
self.sendAncillaryIfPossible( |
| 4212 |
MSG, |
| 4213 |
[(socket.SOL_SOCKET, |
| 4214 |
socket.SCM_RIGHTS, |
| 4215 |
array.array("i", [fd0, self.badfd]).tobytes()[:-1]), |
| 4216 |
(socket.SOL_SOCKET, |
| 4217 |
socket.SCM_RIGHTS, |
| 4218 |
array.array("i", [fd1]))]) |
| 4219 |
|
| 4220 |
def checkTruncatedHeader(self, result, ignoreflags=0): |
| 4221 |
# Check that no ancillary data items are returned when data is |
| 4222 |
# truncated inside the cmsghdr structure. |
| 4223 |
msg, ancdata, flags, addr = result |
| 4224 |
self.assertEqual(msg, MSG) |
| 4225 |
self.checkRecvmsgAddress(addr, self.cli_addr) |
| 4226 |
self.assertEqual(ancdata, []) |
| 4227 |
self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC, |
| 4228 |
ignore=ignoreflags) |
| 4229 |
|
| 4230 |
@skipForRefleakHuntinIf(sys.platform == "darwin", "#80931") |
| 4231 |
def testCmsgTruncNoBufSize(self): |
| 4232 |
# Check that no ancillary data is received when no buffer size |
| 4233 |
# is specified. |
| 4234 |
self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG)), |
| 4235 |
# BSD seems to set MSG_CTRUNC only |
| 4236 |
# if an item has been partially |
| 4237 |
# received. |
| 4238 |
ignoreflags=socket.MSG_CTRUNC) |
| 4239 |
|
| 4240 |
@testCmsgTruncNoBufSize.client_skip |
| 4241 |
def _testCmsgTruncNoBufSize(self): |
| 4242 |
self.createAndSendFDs(1) |
| 4243 |
|
| 4244 |
@skipForRefleakHuntinIf(sys.platform == "darwin", "#80931") |
| 4245 |
def testCmsgTrunc0(self): |
| 4246 |
# Check that no ancillary data is received when buffer size is 0. |
| 4247 |
self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG), 0), |
| 4248 |
ignoreflags=socket.MSG_CTRUNC) |
| 4249 |
|
| 4250 |
@testCmsgTrunc0.client_skip |
| 4251 |
def _testCmsgTrunc0(self): |
| 4252 |
self.createAndSendFDs(1) |
| 4253 |
|
| 4254 |
# Check that no ancillary data is returned for various non-zero |
| 4255 |
# (but still too small) buffer sizes. |
| 4256 |
|
| 4257 |
@skipForRefleakHuntinIf(sys.platform == "darwin", "#80931") |
| 4258 |
def testCmsgTrunc1(self): |
| 4259 |
self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG), 1)) |
| 4260 |
|
| 4261 |
@testCmsgTrunc1.client_skip |
| 4262 |
def _testCmsgTrunc1(self): |
| 4263 |
self.createAndSendFDs(1) |
| 4264 |
|
| 4265 |
@skipForRefleakHuntinIf(sys.platform == "darwin", "#80931") |
| 4266 |
def testCmsgTrunc2Int(self): |
| 4267 |
# The cmsghdr structure has at least three members, two of |
| 4268 |
# which are ints, so we still shouldn't see any ancillary |
| 4269 |
# data. |
| 4270 |
self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG), |
| 4271 |
SIZEOF_INT * 2)) |
| 4272 |
|
| 4273 |
@testCmsgTrunc2Int.client_skip |
| 4274 |
def _testCmsgTrunc2Int(self): |
| 4275 |
self.createAndSendFDs(1) |
| 4276 |
|
| 4277 |
@skipForRefleakHuntinIf(sys.platform == "darwin", "#80931") |
| 4278 |
def testCmsgTruncLen0Minus1(self): |
| 4279 |
self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG), |
| 4280 |
socket.CMSG_LEN(0) - 1)) |
| 4281 |
|
| 4282 |
@testCmsgTruncLen0Minus1.client_skip |
| 4283 |
def _testCmsgTruncLen0Minus1(self): |
| 4284 |
self.createAndSendFDs(1) |
| 4285 |
|
| 4286 |
# The following tests try to truncate the control message in the |
| 4287 |
# middle of the FD array. |
| 4288 |
|
| 4289 |
def checkTruncatedArray(self, ancbuf, maxdata, mindata=0): |
| 4290 |
# Check that file descriptor data is truncated to between |
| 4291 |
# mindata and maxdata bytes when received with buffer size |
| 4292 |
# ancbuf, and that any complete file descriptor numbers are |
| 4293 |
# valid. |
| 4294 |
with downgrade_malformed_data_warning(): # TODO: gh-110012 |
| 4295 |
msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, |
| 4296 |
len(MSG), ancbuf) |
| 4297 |
self.assertEqual(msg, MSG) |
| 4298 |
self.checkRecvmsgAddress(addr, self.cli_addr) |
| 4299 |
self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC) |
| 4300 |
|
| 4301 |
if mindata == 0 and ancdata == []: |
| 4302 |
return |
| 4303 |
self.assertEqual(len(ancdata), 1) |
| 4304 |
cmsg_level, cmsg_type, cmsg_data = ancdata[0] |
| 4305 |
self.assertEqual(cmsg_level, socket.SOL_SOCKET) |
| 4306 |
self.assertEqual(cmsg_type, socket.SCM_RIGHTS) |
| 4307 |
self.assertGreaterEqual(len(cmsg_data), mindata) |
| 4308 |
self.assertLessEqual(len(cmsg_data), maxdata) |
| 4309 |
fds = array.array("i") |
| 4310 |
fds.frombytes(cmsg_data[: |
| 4311 |
len(cmsg_data) - (len(cmsg_data) % fds.itemsize)]) |
| 4312 |
self.checkFDs(fds) |
| 4313 |
|
| 4314 |
@skipForRefleakHuntinIf(sys.platform == "darwin", "#80931") |
| 4315 |
def testCmsgTruncLen0(self): |
| 4316 |
self.checkTruncatedArray(ancbuf=socket.CMSG_LEN(0), maxdata=0) |
| 4317 |
|
| 4318 |
@testCmsgTruncLen0.client_skip |
| 4319 |
def _testCmsgTruncLen0(self): |
| 4320 |
self.createAndSendFDs(1) |
| 4321 |
|
| 4322 |
@skipForRefleakHuntinIf(sys.platform == "darwin", "#80931") |
| 4323 |
def testCmsgTruncLen0Plus1(self): |
| 4324 |
self.checkTruncatedArray(ancbuf=socket.CMSG_LEN(0) + 1, maxdata=1) |
| 4325 |
|
| 4326 |
@testCmsgTruncLen0Plus1.client_skip |
| 4327 |
def _testCmsgTruncLen0Plus1(self): |
| 4328 |
self.createAndSendFDs(2) |
| 4329 |
|
| 4330 |
@skipForRefleakHuntinIf(sys.platform == "darwin", "#80931") |
| 4331 |
def testCmsgTruncLen1(self): |
| 4332 |
self.checkTruncatedArray(ancbuf=socket.CMSG_LEN(SIZEOF_INT), |
| 4333 |
maxdata=SIZEOF_INT) |
| 4334 |
|
| 4335 |
@testCmsgTruncLen1.client_skip |
| 4336 |
def _testCmsgTruncLen1(self): |
| 4337 |
self.createAndSendFDs(2) |
| 4338 |
|
| 4339 |
|
| 4340 |
@skipForRefleakHuntinIf(sys.platform == "darwin", "#80931") |
| 4341 |
def testCmsgTruncLen2Minus1(self): |
| 4342 |
self.checkTruncatedArray(ancbuf=socket.CMSG_LEN(2 * SIZEOF_INT) - 1, |
| 4343 |
maxdata=(2 * SIZEOF_INT) - 1) |
| 4344 |
|
| 4345 |
@testCmsgTruncLen2Minus1.client_skip |
| 4346 |
def _testCmsgTruncLen2Minus1(self): |
| 4347 |
self.createAndSendFDs(2) |
| 4348 |
|
| 4349 |
|
| 4350 |
class RFC3542AncillaryTest(SendrecvmsgServerTimeoutBase): |
| 4351 |
# Test sendmsg() and recvmsg[_into]() using the ancillary data |
| 4352 |
# features of the RFC 3542 Advanced Sockets API for IPv6. |
| 4353 |
# Currently we can only handle certain data items (e.g. traffic |
| 4354 |
# class, hop limit, MTU discovery and fragmentation settings) |
| 4355 |
# without resorting to unportable means such as the struct module, |
| 4356 |
# but the tests here are aimed at testing the ancillary data |
| 4357 |
# handling in sendmsg() and recvmsg() rather than the IPv6 API |
| 4358 |
# itself. |
| 4359 |
|
| 4360 |
# Test value to use when setting hop limit of packet |
| 4361 |
hop_limit = 2 |
| 4362 |
|
| 4363 |
# Test value to use when setting traffic class of packet. |
| 4364 |
# -1 means "use kernel default". |
| 4365 |
traffic_class = -1 |
| 4366 |
|
| 4367 |
def ancillaryMapping(self, ancdata): |
| 4368 |
# Given ancillary data list ancdata, return a mapping from |
| 4369 |
# pairs (cmsg_level, cmsg_type) to corresponding cmsg_data. |
| 4370 |
# Check that no (level, type) pair appears more than once. |
| 4371 |
d = {} |
| 4372 |
for cmsg_level, cmsg_type, cmsg_data in ancdata: |
| 4373 |
self.assertNotIn((cmsg_level, cmsg_type), d) |
| 4374 |
d[(cmsg_level, cmsg_type)] = cmsg_data |
| 4375 |
return d |
| 4376 |
|
| 4377 |
def checkHopLimit(self, ancbufsize, maxhop=255, ignoreflags=0): |
| 4378 |
# Receive hop limit into ancbufsize bytes of ancillary data |
| 4379 |
# space. Check that data is MSG, ancillary data is not |
| 4380 |
# truncated (but ignore any flags in ignoreflags), and hop |
| 4381 |
# limit is between 0 and maxhop inclusive. |
| 4382 |
self.serv_sock.setsockopt(socket.IPPROTO_IPV6, |
| 4383 |
socket.IPV6_RECVHOPLIMIT, 1) |
| 4384 |
self.misc_event.set() |
| 4385 |
msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, |
| 4386 |
len(MSG), ancbufsize) |
| 4387 |
|
| 4388 |
self.assertEqual(msg, MSG) |
| 4389 |
self.checkRecvmsgAddress(addr, self.cli_addr) |
| 4390 |
self.checkFlags(flags, eor=True, checkunset=socket.MSG_CTRUNC, |
| 4391 |
ignore=ignoreflags) |
| 4392 |
|
| 4393 |
self.assertEqual(len(ancdata), 1) |
| 4394 |
self.assertIsInstance(ancdata[0], tuple) |
| 4395 |
cmsg_level, cmsg_type, cmsg_data = ancdata[0] |
| 4396 |
self.assertEqual(cmsg_level, socket.IPPROTO_IPV6) |
| 4397 |
self.assertEqual(cmsg_type, socket.IPV6_HOPLIMIT) |
| 4398 |
self.assertIsInstance(cmsg_data, bytes) |
| 4399 |
self.assertEqual(len(cmsg_data), SIZEOF_INT) |
| 4400 |
a = array.array("i") |
| 4401 |
a.frombytes(cmsg_data) |
| 4402 |
self.assertGreaterEqual(a[0], 0) |
| 4403 |
self.assertLessEqual(a[0], maxhop) |
| 4404 |
|
| 4405 |
@requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT") |
| 4406 |
def testRecvHopLimit(self): |
| 4407 |
# Test receiving the packet hop limit as ancillary data. |
| 4408 |
self.checkHopLimit(ancbufsize=10240) |
| 4409 |
|
| 4410 |
@testRecvHopLimit.client_skip |
| 4411 |
def _testRecvHopLimit(self): |
| 4412 |
# Need to wait until server has asked to receive ancillary |
| 4413 |
# data, as implementations are not required to buffer it |
| 4414 |
# otherwise. |
| 4415 |
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
| 4416 |
self.sendToServer(MSG) |
| 4417 |
|
| 4418 |
@requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT") |
| 4419 |
def testRecvHopLimitCMSG_SPACE(self): |
| 4420 |
# Test receiving hop limit, using CMSG_SPACE to calculate buffer size. |
| 4421 |
self.checkHopLimit(ancbufsize=socket.CMSG_SPACE(SIZEOF_INT)) |
| 4422 |
|
| 4423 |
@testRecvHopLimitCMSG_SPACE.client_skip |
| 4424 |
def _testRecvHopLimitCMSG_SPACE(self): |
| 4425 |
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
| 4426 |
self.sendToServer(MSG) |
| 4427 |
|
| 4428 |
# Could test receiving into buffer sized using CMSG_LEN, but RFC |
| 4429 |
# 3542 says portable applications must provide space for trailing |
| 4430 |
# padding. Implementations may set MSG_CTRUNC if there isn't |
| 4431 |
# enough space for the padding. |
| 4432 |
|
| 4433 |
@requireAttrs(socket.socket, "sendmsg") |
| 4434 |
@requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT") |
| 4435 |
def testSetHopLimit(self): |
| 4436 |
# Test setting hop limit on outgoing packet and receiving it |
| 4437 |
# at the other end. |
| 4438 |
self.checkHopLimit(ancbufsize=10240, maxhop=self.hop_limit) |
| 4439 |
|
| 4440 |
@testSetHopLimit.client_skip |
| 4441 |
def _testSetHopLimit(self): |
| 4442 |
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
| 4443 |
self.assertEqual( |
| 4444 |
self.sendmsgToServer([MSG], |
| 4445 |
[(socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT, |
| 4446 |
array.array("i", [self.hop_limit]))]), |
| 4447 |
len(MSG)) |
| 4448 |
|
| 4449 |
def checkTrafficClassAndHopLimit(self, ancbufsize, maxhop=255, |
| 4450 |
ignoreflags=0): |
| 4451 |
# Receive traffic class and hop limit into ancbufsize bytes of |
| 4452 |
# ancillary data space. Check that data is MSG, ancillary |
| 4453 |
# data is not truncated (but ignore any flags in ignoreflags), |
| 4454 |
# and traffic class and hop limit are in range (hop limit no |
| 4455 |
# more than maxhop). |
| 4456 |
self.serv_sock.setsockopt(socket.IPPROTO_IPV6, |
| 4457 |
socket.IPV6_RECVHOPLIMIT, 1) |
| 4458 |
self.serv_sock.setsockopt(socket.IPPROTO_IPV6, |
| 4459 |
socket.IPV6_RECVTCLASS, 1) |
| 4460 |
self.misc_event.set() |
| 4461 |
msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, |
| 4462 |
len(MSG), ancbufsize) |
| 4463 |
|
| 4464 |
self.assertEqual(msg, MSG) |
| 4465 |
self.checkRecvmsgAddress(addr, self.cli_addr) |
| 4466 |
self.checkFlags(flags, eor=True, checkunset=socket.MSG_CTRUNC, |
| 4467 |
ignore=ignoreflags) |
| 4468 |
self.assertEqual(len(ancdata), 2) |
| 4469 |
ancmap = self.ancillaryMapping(ancdata) |
| 4470 |
|
| 4471 |
tcdata = ancmap[(socket.IPPROTO_IPV6, socket.IPV6_TCLASS)] |
| 4472 |
self.assertEqual(len(tcdata), SIZEOF_INT) |
| 4473 |
a = array.array("i") |
| 4474 |
a.frombytes(tcdata) |
| 4475 |
self.assertGreaterEqual(a[0], 0) |
| 4476 |
self.assertLessEqual(a[0], 255) |
| 4477 |
|
| 4478 |
hldata = ancmap[(socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT)] |
| 4479 |
self.assertEqual(len(hldata), SIZEOF_INT) |
| 4480 |
a = array.array("i") |
| 4481 |
a.frombytes(hldata) |
| 4482 |
self.assertGreaterEqual(a[0], 0) |
| 4483 |
self.assertLessEqual(a[0], maxhop) |
| 4484 |
|
| 4485 |
@requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT", |
| 4486 |
"IPV6_RECVTCLASS", "IPV6_TCLASS") |
| 4487 |
def testRecvTrafficClassAndHopLimit(self): |
| 4488 |
# Test receiving traffic class and hop limit as ancillary data. |
| 4489 |
self.checkTrafficClassAndHopLimit(ancbufsize=10240) |
| 4490 |
|
| 4491 |
@testRecvTrafficClassAndHopLimit.client_skip |
| 4492 |
def _testRecvTrafficClassAndHopLimit(self): |
| 4493 |
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
| 4494 |
self.sendToServer(MSG) |
| 4495 |
|
| 4496 |
@requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT", |
| 4497 |
"IPV6_RECVTCLASS", "IPV6_TCLASS") |
| 4498 |
def testRecvTrafficClassAndHopLimitCMSG_SPACE(self): |
| 4499 |
# Test receiving traffic class and hop limit, using |
| 4500 |
# CMSG_SPACE() to calculate buffer size. |
| 4501 |
self.checkTrafficClassAndHopLimit( |
| 4502 |
ancbufsize=socket.CMSG_SPACE(SIZEOF_INT) * 2) |
| 4503 |
|
| 4504 |
@testRecvTrafficClassAndHopLimitCMSG_SPACE.client_skip |
| 4505 |
def _testRecvTrafficClassAndHopLimitCMSG_SPACE(self): |
| 4506 |
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
| 4507 |
self.sendToServer(MSG) |
| 4508 |
|
| 4509 |
@requireAttrs(socket.socket, "sendmsg") |
| 4510 |
@requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT", |
| 4511 |
"IPV6_RECVTCLASS", "IPV6_TCLASS") |
| 4512 |
def testSetTrafficClassAndHopLimit(self): |
| 4513 |
# Test setting traffic class and hop limit on outgoing packet, |
| 4514 |
# and receiving them at the other end. |
| 4515 |
self.checkTrafficClassAndHopLimit(ancbufsize=10240, |
| 4516 |
maxhop=self.hop_limit) |
| 4517 |
|
| 4518 |
@testSetTrafficClassAndHopLimit.client_skip |
| 4519 |
def _testSetTrafficClassAndHopLimit(self): |
| 4520 |
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
| 4521 |
self.assertEqual( |
| 4522 |
self.sendmsgToServer([MSG], |
| 4523 |
[(socket.IPPROTO_IPV6, socket.IPV6_TCLASS, |
| 4524 |
array.array("i", [self.traffic_class])), |
| 4525 |
(socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT, |
| 4526 |
array.array("i", [self.hop_limit]))]), |
| 4527 |
len(MSG)) |
| 4528 |
|
| 4529 |
@requireAttrs(socket.socket, "sendmsg") |
| 4530 |
@requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT", |
| 4531 |
"IPV6_RECVTCLASS", "IPV6_TCLASS") |
| 4532 |
def testOddCmsgSize(self): |
| 4533 |
# Try to send ancillary data with first item one byte too |
| 4534 |
# long. Fall back to sending with correct size if this fails, |
| 4535 |
# and check that second item was handled correctly. |
| 4536 |
self.checkTrafficClassAndHopLimit(ancbufsize=10240, |
| 4537 |
maxhop=self.hop_limit) |
| 4538 |
|
| 4539 |
@testOddCmsgSize.client_skip |
| 4540 |
def _testOddCmsgSize(self): |
| 4541 |
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
| 4542 |
try: |
| 4543 |
nbytes = self.sendmsgToServer( |
| 4544 |
[MSG], |
| 4545 |
[(socket.IPPROTO_IPV6, socket.IPV6_TCLASS, |
| 4546 |
array.array("i", [self.traffic_class]).tobytes() + b"\x00"), |
| 4547 |
(socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT, |
| 4548 |
array.array("i", [self.hop_limit]))]) |
| 4549 |
except OSError as e: |
| 4550 |
self.assertIsInstance(e.errno, int) |
| 4551 |
nbytes = self.sendmsgToServer( |
| 4552 |
[MSG], |
| 4553 |
[(socket.IPPROTO_IPV6, socket.IPV6_TCLASS, |
| 4554 |
array.array("i", [self.traffic_class])), |
| 4555 |
(socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT, |
| 4556 |
array.array("i", [self.hop_limit]))]) |
| 4557 |
self.assertEqual(nbytes, len(MSG)) |
| 4558 |
|
| 4559 |
# Tests for proper handling of truncated ancillary data |
| 4560 |
|
| 4561 |
def checkHopLimitTruncatedHeader(self, ancbufsize, ignoreflags=0): |
| 4562 |
# Receive hop limit into ancbufsize bytes of ancillary data |
| 4563 |
# space, which should be too small to contain the ancillary |
| 4564 |
# data header (if ancbufsize is None, pass no second argument |
| 4565 |
# to recvmsg()). Check that data is MSG, MSG_CTRUNC is set |
| 4566 |
# (unless included in ignoreflags), and no ancillary data is |
| 4567 |
# returned. |
| 4568 |
self.serv_sock.setsockopt(socket.IPPROTO_IPV6, |
| 4569 |
socket.IPV6_RECVHOPLIMIT, 1) |
| 4570 |
self.misc_event.set() |
| 4571 |
args = () if ancbufsize is None else (ancbufsize,) |
| 4572 |
msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, |
| 4573 |
len(MSG), *args) |
| 4574 |
|
| 4575 |
self.assertEqual(msg, MSG) |
| 4576 |
self.checkRecvmsgAddress(addr, self.cli_addr) |
| 4577 |
self.assertEqual(ancdata, []) |
| 4578 |
self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC, |
| 4579 |
ignore=ignoreflags) |
| 4580 |
|
| 4581 |
@requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT") |
| 4582 |
def testCmsgTruncNoBufSize(self): |
| 4583 |
# Check that no ancillary data is received when no ancillary |
| 4584 |
# buffer size is provided. |
| 4585 |
self.checkHopLimitTruncatedHeader(ancbufsize=None, |
| 4586 |
# BSD seems to set |
| 4587 |
# MSG_CTRUNC only if an item |
| 4588 |
# has been partially |
| 4589 |
# received. |
| 4590 |
ignoreflags=socket.MSG_CTRUNC) |
| 4591 |
|
| 4592 |
@testCmsgTruncNoBufSize.client_skip |
| 4593 |
def _testCmsgTruncNoBufSize(self): |
| 4594 |
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
| 4595 |
self.sendToServer(MSG) |
| 4596 |
|
| 4597 |
@requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT") |
| 4598 |
def testSingleCmsgTrunc0(self): |
| 4599 |
# Check that no ancillary data is received when ancillary |
| 4600 |
# buffer size is zero. |
| 4601 |
self.checkHopLimitTruncatedHeader(ancbufsize=0, |
| 4602 |
ignoreflags=socket.MSG_CTRUNC) |
| 4603 |
|
| 4604 |
@testSingleCmsgTrunc0.client_skip |
| 4605 |
def _testSingleCmsgTrunc0(self): |
| 4606 |
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
| 4607 |
self.sendToServer(MSG) |
| 4608 |
|
| 4609 |
# Check that no ancillary data is returned for various non-zero |
| 4610 |
# (but still too small) buffer sizes. |
| 4611 |
|
| 4612 |
@requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT") |
| 4613 |
def testSingleCmsgTrunc1(self): |
| 4614 |
self.checkHopLimitTruncatedHeader(ancbufsize=1) |
| 4615 |
|
| 4616 |
@testSingleCmsgTrunc1.client_skip |
| 4617 |
def _testSingleCmsgTrunc1(self): |
| 4618 |
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
| 4619 |
self.sendToServer(MSG) |
| 4620 |
|
| 4621 |
@requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT") |
| 4622 |
def testSingleCmsgTrunc2Int(self): |
| 4623 |
self.checkHopLimitTruncatedHeader(ancbufsize=2 * SIZEOF_INT) |
| 4624 |
|
| 4625 |
@testSingleCmsgTrunc2Int.client_skip |
| 4626 |
def _testSingleCmsgTrunc2Int(self): |
| 4627 |
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
| 4628 |
self.sendToServer(MSG) |
| 4629 |
|
| 4630 |
@requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT") |
| 4631 |
def testSingleCmsgTruncLen0Minus1(self): |
| 4632 |
self.checkHopLimitTruncatedHeader(ancbufsize=socket.CMSG_LEN(0) - 1) |
| 4633 |
|
| 4634 |
@testSingleCmsgTruncLen0Minus1.client_skip |
| 4635 |
def _testSingleCmsgTruncLen0Minus1(self): |
| 4636 |
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
| 4637 |
self.sendToServer(MSG) |
| 4638 |
|
| 4639 |
@requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT") |
| 4640 |
def testSingleCmsgTruncInData(self): |
| 4641 |
# Test truncation of a control message inside its associated |
| 4642 |
# data. The message may be returned with its data truncated, |
| 4643 |
# or not returned at all. |
| 4644 |
self.serv_sock.setsockopt(socket.IPPROTO_IPV6, |
| 4645 |
socket.IPV6_RECVHOPLIMIT, 1) |
| 4646 |
self.misc_event.set() |
| 4647 |
with downgrade_malformed_data_warning(): # TODO: gh-110012 |
| 4648 |
msg, ancdata, flags, addr = self.doRecvmsg( |
| 4649 |
self.serv_sock, len(MSG), socket.CMSG_LEN(SIZEOF_INT) - 1) |
| 4650 |
|
| 4651 |
self.assertEqual(msg, MSG) |
| 4652 |
self.checkRecvmsgAddress(addr, self.cli_addr) |
| 4653 |
self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC) |
| 4654 |
|
| 4655 |
self.assertLessEqual(len(ancdata), 1) |
| 4656 |
if ancdata: |
| 4657 |
cmsg_level, cmsg_type, cmsg_data = ancdata[0] |
| 4658 |
self.assertEqual(cmsg_level, socket.IPPROTO_IPV6) |
| 4659 |
self.assertEqual(cmsg_type, socket.IPV6_HOPLIMIT) |
| 4660 |
self.assertLess(len(cmsg_data), SIZEOF_INT) |
| 4661 |
|
| 4662 |
@testSingleCmsgTruncInData.client_skip |
| 4663 |
def _testSingleCmsgTruncInData(self): |
| 4664 |
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
| 4665 |
self.sendToServer(MSG) |
| 4666 |
|
| 4667 |
def checkTruncatedSecondHeader(self, ancbufsize, ignoreflags=0): |
| 4668 |
# Receive traffic class and hop limit into ancbufsize bytes of |
| 4669 |
# ancillary data space, which should be large enough to |
| 4670 |
# contain the first item, but too small to contain the header |
| 4671 |
# of the second. Check that data is MSG, MSG_CTRUNC is set |
| 4672 |
# (unless included in ignoreflags), and only one ancillary |
| 4673 |
# data item is returned. |
| 4674 |
self.serv_sock.setsockopt(socket.IPPROTO_IPV6, |
| 4675 |
socket.IPV6_RECVHOPLIMIT, 1) |
| 4676 |
self.serv_sock.setsockopt(socket.IPPROTO_IPV6, |
| 4677 |
socket.IPV6_RECVTCLASS, 1) |
| 4678 |
self.misc_event.set() |
| 4679 |
msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, |
| 4680 |
len(MSG), ancbufsize) |
| 4681 |
|
| 4682 |
self.assertEqual(msg, MSG) |
| 4683 |
self.checkRecvmsgAddress(addr, self.cli_addr) |
| 4684 |
self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC, |
| 4685 |
ignore=ignoreflags) |
| 4686 |
|
| 4687 |
self.assertEqual(len(ancdata), 1) |
| 4688 |
cmsg_level, cmsg_type, cmsg_data = ancdata[0] |
| 4689 |
self.assertEqual(cmsg_level, socket.IPPROTO_IPV6) |
| 4690 |
self.assertIn(cmsg_type, {socket.IPV6_TCLASS, socket.IPV6_HOPLIMIT}) |
| 4691 |
self.assertEqual(len(cmsg_data), SIZEOF_INT) |
| 4692 |
a = array.array("i") |
| 4693 |
a.frombytes(cmsg_data) |
| 4694 |
self.assertGreaterEqual(a[0], 0) |
| 4695 |
self.assertLessEqual(a[0], 255) |
| 4696 |
|
| 4697 |
# Try the above test with various buffer sizes. |
| 4698 |
|
| 4699 |
@requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT", |
| 4700 |
"IPV6_RECVTCLASS", "IPV6_TCLASS") |
| 4701 |
def testSecondCmsgTrunc0(self): |
| 4702 |
self.checkTruncatedSecondHeader(socket.CMSG_SPACE(SIZEOF_INT), |
| 4703 |
ignoreflags=socket.MSG_CTRUNC) |
| 4704 |
|
| 4705 |
@testSecondCmsgTrunc0.client_skip |
| 4706 |
def _testSecondCmsgTrunc0(self): |
| 4707 |
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
| 4708 |
self.sendToServer(MSG) |
| 4709 |
|
| 4710 |
@requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT", |
| 4711 |
"IPV6_RECVTCLASS", "IPV6_TCLASS") |
| 4712 |
def testSecondCmsgTrunc1(self): |
| 4713 |
self.checkTruncatedSecondHeader(socket.CMSG_SPACE(SIZEOF_INT) + 1) |
| 4714 |
|
| 4715 |
@testSecondCmsgTrunc1.client_skip |
| 4716 |
def _testSecondCmsgTrunc1(self): |
| 4717 |
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
| 4718 |
self.sendToServer(MSG) |
| 4719 |
|
| 4720 |
@requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT", |
| 4721 |
"IPV6_RECVTCLASS", "IPV6_TCLASS") |
| 4722 |
def testSecondCmsgTrunc2Int(self): |
| 4723 |
self.checkTruncatedSecondHeader(socket.CMSG_SPACE(SIZEOF_INT) + |
| 4724 |
2 * SIZEOF_INT) |
| 4725 |
|
| 4726 |
@testSecondCmsgTrunc2Int.client_skip |
| 4727 |
def _testSecondCmsgTrunc2Int(self): |
| 4728 |
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
| 4729 |
self.sendToServer(MSG) |
| 4730 |
|
| 4731 |
@requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT", |
| 4732 |
"IPV6_RECVTCLASS", "IPV6_TCLASS") |
| 4733 |
def testSecondCmsgTruncLen0Minus1(self): |
| 4734 |
self.checkTruncatedSecondHeader(socket.CMSG_SPACE(SIZEOF_INT) + |
| 4735 |
socket.CMSG_LEN(0) - 1) |
| 4736 |
|
| 4737 |
@testSecondCmsgTruncLen0Minus1.client_skip |
| 4738 |
def _testSecondCmsgTruncLen0Minus1(self): |
| 4739 |
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
| 4740 |
self.sendToServer(MSG) |
| 4741 |
|
| 4742 |
@requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT", |
| 4743 |
"IPV6_RECVTCLASS", "IPV6_TCLASS") |
| 4744 |
def testSecondCmsgTruncInData(self): |
| 4745 |
# Test truncation of the second of two control messages inside |
| 4746 |
# its associated data. |
| 4747 |
self.serv_sock.setsockopt(socket.IPPROTO_IPV6, |
| 4748 |
socket.IPV6_RECVHOPLIMIT, 1) |
| 4749 |
self.serv_sock.setsockopt(socket.IPPROTO_IPV6, |
| 4750 |
socket.IPV6_RECVTCLASS, 1) |
| 4751 |
self.misc_event.set() |
| 4752 |
with downgrade_malformed_data_warning(): # TODO: gh-110012 |
| 4753 |
msg, ancdata, flags, addr = self.doRecvmsg( |
| 4754 |
self.serv_sock, len(MSG), |
| 4755 |
socket.CMSG_SPACE(SIZEOF_INT) + socket.CMSG_LEN(SIZEOF_INT) - 1) |
| 4756 |
|
| 4757 |
self.assertEqual(msg, MSG) |
| 4758 |
self.checkRecvmsgAddress(addr, self.cli_addr) |
| 4759 |
self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC) |
| 4760 |
|
| 4761 |
cmsg_types = {socket.IPV6_TCLASS, socket.IPV6_HOPLIMIT} |
| 4762 |
|
| 4763 |
cmsg_level, cmsg_type, cmsg_data = ancdata.pop(0) |
| 4764 |
self.assertEqual(cmsg_level, socket.IPPROTO_IPV6) |
| 4765 |
cmsg_types.remove(cmsg_type) |
| 4766 |
self.assertEqual(len(cmsg_data), SIZEOF_INT) |
| 4767 |
a = array.array("i") |
| 4768 |
a.frombytes(cmsg_data) |
| 4769 |
self.assertGreaterEqual(a[0], 0) |
| 4770 |
self.assertLessEqual(a[0], 255) |
| 4771 |
|
| 4772 |
if ancdata: |
| 4773 |
cmsg_level, cmsg_type, cmsg_data = ancdata.pop(0) |
| 4774 |
self.assertEqual(cmsg_level, socket.IPPROTO_IPV6) |
| 4775 |
cmsg_types.remove(cmsg_type) |
| 4776 |
self.assertLess(len(cmsg_data), SIZEOF_INT) |
| 4777 |
|
| 4778 |
self.assertEqual(ancdata, []) |
| 4779 |
|
| 4780 |
@testSecondCmsgTruncInData.client_skip |
| 4781 |
def _testSecondCmsgTruncInData(self): |
| 4782 |
self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
| 4783 |
self.sendToServer(MSG) |
| 4784 |
|
| 4785 |
|
| 4786 |
# Derive concrete test classes for different socket types. |
| 4787 |
|
| 4788 |
class SendrecvmsgUDPTestBase(SendrecvmsgDgramFlagsBase, |
| 4789 |
SendrecvmsgConnectionlessBase, |
| 4790 |
ThreadedSocketTestMixin, UDPTestBase): |
| 4791 |
pass |
| 4792 |
|
| 4793 |
@requireAttrs(socket.socket, "sendmsg") |
| 4794 |
class SendmsgUDPTest(SendmsgConnectionlessTests, SendrecvmsgUDPTestBase): |
| 4795 |
pass |
| 4796 |
|
| 4797 |
@requireAttrs(socket.socket, "recvmsg") |
| 4798 |
class RecvmsgUDPTest(RecvmsgTests, SendrecvmsgUDPTestBase): |
| 4799 |
pass |
| 4800 |
|
| 4801 |
@requireAttrs(socket.socket, "recvmsg_into") |
| 4802 |
class RecvmsgIntoUDPTest(RecvmsgIntoTests, SendrecvmsgUDPTestBase): |
| 4803 |
pass |
| 4804 |
|
| 4805 |
|
| 4806 |
class SendrecvmsgUDP6TestBase(SendrecvmsgDgramFlagsBase, |
| 4807 |
SendrecvmsgConnectionlessBase, |
| 4808 |
ThreadedSocketTestMixin, UDP6TestBase): |
| 4809 |
|
| 4810 |
def checkRecvmsgAddress(self, addr1, addr2): |
| 4811 |
# Called to compare the received address with the address of |
| 4812 |
# the peer, ignoring scope ID |
| 4813 |
self.assertEqual(addr1[:-1], addr2[:-1]) |
| 4814 |
|
| 4815 |
@requireAttrs(socket.socket, "sendmsg") |
| 4816 |
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.') |
| 4817 |
@requireSocket("AF_INET6", "SOCK_DGRAM") |
| 4818 |
class SendmsgUDP6Test(SendmsgConnectionlessTests, SendrecvmsgUDP6TestBase): |
| 4819 |
pass |
| 4820 |
|
| 4821 |
@requireAttrs(socket.socket, "recvmsg") |
| 4822 |
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.') |
| 4823 |
@requireSocket("AF_INET6", "SOCK_DGRAM") |
| 4824 |
class RecvmsgUDP6Test(RecvmsgTests, SendrecvmsgUDP6TestBase): |
| 4825 |
pass |
| 4826 |
|
| 4827 |
@requireAttrs(socket.socket, "recvmsg_into") |
| 4828 |
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.') |
| 4829 |
@requireSocket("AF_INET6", "SOCK_DGRAM") |
| 4830 |
class RecvmsgIntoUDP6Test(RecvmsgIntoTests, SendrecvmsgUDP6TestBase): |
| 4831 |
pass |
| 4832 |
|
| 4833 |
@requireAttrs(socket.socket, "recvmsg") |
| 4834 |
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.') |
| 4835 |
@requireAttrs(socket, "IPPROTO_IPV6") |
| 4836 |
@requireSocket("AF_INET6", "SOCK_DGRAM") |
| 4837 |
class RecvmsgRFC3542AncillaryUDP6Test(RFC3542AncillaryTest, |
| 4838 |
SendrecvmsgUDP6TestBase): |
| 4839 |
pass |
| 4840 |
|
| 4841 |
@requireAttrs(socket.socket, "recvmsg_into") |
| 4842 |
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.') |
| 4843 |
@requireAttrs(socket, "IPPROTO_IPV6") |
| 4844 |
@requireSocket("AF_INET6", "SOCK_DGRAM") |
| 4845 |
class RecvmsgIntoRFC3542AncillaryUDP6Test(RecvmsgIntoMixin, |
| 4846 |
RFC3542AncillaryTest, |
| 4847 |
SendrecvmsgUDP6TestBase): |
| 4848 |
pass |
| 4849 |
|
| 4850 |
|
| 4851 |
@unittest.skipUnless(HAVE_SOCKET_UDPLITE, |
| 4852 |
'UDPLITE sockets required for this test.') |
| 4853 |
class SendrecvmsgUDPLITETestBase(SendrecvmsgDgramFlagsBase, |
| 4854 |
SendrecvmsgConnectionlessBase, |
| 4855 |
ThreadedSocketTestMixin, UDPLITETestBase): |
| 4856 |
pass |
| 4857 |
|
| 4858 |
@unittest.skipUnless(HAVE_SOCKET_UDPLITE, |
| 4859 |
'UDPLITE sockets required for this test.') |
| 4860 |
@requireAttrs(socket.socket, "sendmsg") |
| 4861 |
class SendmsgUDPLITETest(SendmsgConnectionlessTests, SendrecvmsgUDPLITETestBase): |
| 4862 |
pass |
| 4863 |
|
| 4864 |
@unittest.skipUnless(HAVE_SOCKET_UDPLITE, |
| 4865 |
'UDPLITE sockets required for this test.') |
| 4866 |
@requireAttrs(socket.socket, "recvmsg") |
| 4867 |
class RecvmsgUDPLITETest(RecvmsgTests, SendrecvmsgUDPLITETestBase): |
| 4868 |
pass |
| 4869 |
|
| 4870 |
@unittest.skipUnless(HAVE_SOCKET_UDPLITE, |
| 4871 |
'UDPLITE sockets required for this test.') |
| 4872 |
@requireAttrs(socket.socket, "recvmsg_into") |
| 4873 |
class RecvmsgIntoUDPLITETest(RecvmsgIntoTests, SendrecvmsgUDPLITETestBase): |
| 4874 |
pass |
| 4875 |
|
| 4876 |
|
| 4877 |
@unittest.skipUnless(HAVE_SOCKET_UDPLITE, |
| 4878 |
'UDPLITE sockets required for this test.') |
| 4879 |
class SendrecvmsgUDPLITE6TestBase(SendrecvmsgDgramFlagsBase, |
| 4880 |
SendrecvmsgConnectionlessBase, |
| 4881 |
ThreadedSocketTestMixin, UDPLITE6TestBase): |
| 4882 |
|
| 4883 |
def checkRecvmsgAddress(self, addr1, addr2): |
| 4884 |
# Called to compare the received address with the address of |
| 4885 |
# the peer, ignoring scope ID |
| 4886 |
self.assertEqual(addr1[:-1], addr2[:-1]) |
| 4887 |
|
| 4888 |
@requireAttrs(socket.socket, "sendmsg") |
| 4889 |
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.') |
| 4890 |
@unittest.skipUnless(HAVE_SOCKET_UDPLITE, |
| 4891 |
'UDPLITE sockets required for this test.') |
| 4892 |
@requireSocket("AF_INET6", "SOCK_DGRAM") |
| 4893 |
class SendmsgUDPLITE6Test(SendmsgConnectionlessTests, SendrecvmsgUDPLITE6TestBase): |
| 4894 |
pass |
| 4895 |
|
| 4896 |
@requireAttrs(socket.socket, "recvmsg") |
| 4897 |
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.') |
| 4898 |
@unittest.skipUnless(HAVE_SOCKET_UDPLITE, |
| 4899 |
'UDPLITE sockets required for this test.') |
| 4900 |
@requireSocket("AF_INET6", "SOCK_DGRAM") |
| 4901 |
class RecvmsgUDPLITE6Test(RecvmsgTests, SendrecvmsgUDPLITE6TestBase): |
| 4902 |
pass |
| 4903 |
|
| 4904 |
@requireAttrs(socket.socket, "recvmsg_into") |
| 4905 |
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.') |
| 4906 |
@unittest.skipUnless(HAVE_SOCKET_UDPLITE, |
| 4907 |
'UDPLITE sockets required for this test.') |
| 4908 |
@requireSocket("AF_INET6", "SOCK_DGRAM") |
| 4909 |
class RecvmsgIntoUDPLITE6Test(RecvmsgIntoTests, SendrecvmsgUDPLITE6TestBase): |
| 4910 |
pass |
| 4911 |
|
| 4912 |
@requireAttrs(socket.socket, "recvmsg") |
| 4913 |
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.') |
| 4914 |
@unittest.skipUnless(HAVE_SOCKET_UDPLITE, |
| 4915 |
'UDPLITE sockets required for this test.') |
| 4916 |
@requireAttrs(socket, "IPPROTO_IPV6") |
| 4917 |
@requireSocket("AF_INET6", "SOCK_DGRAM") |
| 4918 |
class RecvmsgRFC3542AncillaryUDPLITE6Test(RFC3542AncillaryTest, |
| 4919 |
SendrecvmsgUDPLITE6TestBase): |
| 4920 |
pass |
| 4921 |
|
| 4922 |
@requireAttrs(socket.socket, "recvmsg_into") |
| 4923 |
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test.') |
| 4924 |
@unittest.skipUnless(HAVE_SOCKET_UDPLITE, |
| 4925 |
'UDPLITE sockets required for this test.') |
| 4926 |
@requireAttrs(socket, "IPPROTO_IPV6") |
| 4927 |
@requireSocket("AF_INET6", "SOCK_DGRAM") |
| 4928 |
class RecvmsgIntoRFC3542AncillaryUDPLITE6Test(RecvmsgIntoMixin, |
| 4929 |
RFC3542AncillaryTest, |
| 4930 |
SendrecvmsgUDPLITE6TestBase): |
| 4931 |
pass |
| 4932 |
|
| 4933 |
|
| 4934 |
class SendrecvmsgTCPTestBase(SendrecvmsgConnectedBase, |
| 4935 |
ConnectedStreamTestMixin, TCPTestBase): |
| 4936 |
pass |
| 4937 |
|
| 4938 |
@requireAttrs(socket.socket, "sendmsg") |
| 4939 |
class SendmsgTCPTest(SendmsgStreamTests, SendrecvmsgTCPTestBase): |
| 4940 |
pass |
| 4941 |
|
| 4942 |
@requireAttrs(socket.socket, "recvmsg") |
| 4943 |
class RecvmsgTCPTest(RecvmsgTests, RecvmsgGenericStreamTests, |
| 4944 |
SendrecvmsgTCPTestBase): |
| 4945 |
pass |
| 4946 |
|
| 4947 |
@requireAttrs(socket.socket, "recvmsg_into") |
| 4948 |
class RecvmsgIntoTCPTest(RecvmsgIntoTests, RecvmsgGenericStreamTests, |
| 4949 |
SendrecvmsgTCPTestBase): |
| 4950 |
pass |
| 4951 |
|
| 4952 |
|
| 4953 |
class SendrecvmsgSCTPStreamTestBase(SendrecvmsgSCTPFlagsBase, |
| 4954 |
SendrecvmsgConnectedBase, |
| 4955 |
ConnectedStreamTestMixin, SCTPStreamBase): |
| 4956 |
pass |
| 4957 |
|
| 4958 |
@requireAttrs(socket.socket, "sendmsg") |
| 4959 |
@unittest.skipIf(AIX, "IPPROTO_SCTP: [Errno 62] Protocol not supported on AIX") |
| 4960 |
@requireSocket("AF_INET", "SOCK_STREAM", "IPPROTO_SCTP") |
| 4961 |
class SendmsgSCTPStreamTest(SendmsgStreamTests, SendrecvmsgSCTPStreamTestBase): |
| 4962 |
pass |
| 4963 |
|
| 4964 |
@requireAttrs(socket.socket, "recvmsg") |
| 4965 |
@unittest.skipIf(AIX, "IPPROTO_SCTP: [Errno 62] Protocol not supported on AIX") |
| 4966 |
@requireSocket("AF_INET", "SOCK_STREAM", "IPPROTO_SCTP") |
| 4967 |
class RecvmsgSCTPStreamTest(RecvmsgTests, RecvmsgGenericStreamTests, |
| 4968 |
SendrecvmsgSCTPStreamTestBase): |
| 4969 |
|
| 4970 |
def testRecvmsgEOF(self): |
| 4971 |
try: |
| 4972 |
super(RecvmsgSCTPStreamTest, self).testRecvmsgEOF() |
| 4973 |
except OSError as e: |
| 4974 |
if e.errno != errno.ENOTCONN: |
| 4975 |
raise |
| 4976 |
self.skipTest("sporadic ENOTCONN (kernel issue?) - see issue #13876") |
| 4977 |
|
| 4978 |
@requireAttrs(socket.socket, "recvmsg_into") |
| 4979 |
@unittest.skipIf(AIX, "IPPROTO_SCTP: [Errno 62] Protocol not supported on AIX") |
| 4980 |
@requireSocket("AF_INET", "SOCK_STREAM", "IPPROTO_SCTP") |
| 4981 |
class RecvmsgIntoSCTPStreamTest(RecvmsgIntoTests, RecvmsgGenericStreamTests, |
| 4982 |
SendrecvmsgSCTPStreamTestBase): |
| 4983 |
|
| 4984 |
def testRecvmsgEOF(self): |
| 4985 |
try: |
| 4986 |
super(RecvmsgIntoSCTPStreamTest, self).testRecvmsgEOF() |
| 4987 |
except OSError as e: |
| 4988 |
if e.errno != errno.ENOTCONN: |
| 4989 |
raise |
| 4990 |
self.skipTest("sporadic ENOTCONN (kernel issue?) - see issue #13876") |
| 4991 |
|
| 4992 |
|
| 4993 |
class SendrecvmsgUnixStreamTestBase(SendrecvmsgConnectedBase, |
| 4994 |
ConnectedStreamTestMixin, UnixStreamBase): |
| 4995 |
pass |
| 4996 |
|
| 4997 |
@requireAttrs(socket.socket, "sendmsg") |
| 4998 |
@requireAttrs(socket, "AF_UNIX") |
| 4999 |
class SendmsgUnixStreamTest(SendmsgStreamTests, SendrecvmsgUnixStreamTestBase): |
| 5000 |
pass |
| 5001 |
|
| 5002 |
@requireAttrs(socket.socket, "recvmsg") |
| 5003 |
@requireAttrs(socket, "AF_UNIX") |
| 5004 |
class RecvmsgUnixStreamTest(RecvmsgTests, RecvmsgGenericStreamTests, |
| 5005 |
SendrecvmsgUnixStreamTestBase): |
| 5006 |
pass |
| 5007 |
|
| 5008 |
@requireAttrs(socket.socket, "recvmsg_into") |
| 5009 |
@requireAttrs(socket, "AF_UNIX") |
| 5010 |
class RecvmsgIntoUnixStreamTest(RecvmsgIntoTests, RecvmsgGenericStreamTests, |
| 5011 |
SendrecvmsgUnixStreamTestBase): |
| 5012 |
pass |
| 5013 |
|
| 5014 |
@requireAttrs(socket.socket, "sendmsg", "recvmsg") |
| 5015 |
@requireAttrs(socket, "AF_UNIX", "SOL_SOCKET", "SCM_RIGHTS") |
| 5016 |
class RecvmsgSCMRightsStreamTest(SCMRightsTest, SendrecvmsgUnixStreamTestBase): |
| 5017 |
pass |
| 5018 |
|
| 5019 |
@requireAttrs(socket.socket, "sendmsg", "recvmsg_into") |
| 5020 |
@requireAttrs(socket, "AF_UNIX", "SOL_SOCKET", "SCM_RIGHTS") |
| 5021 |
class RecvmsgIntoSCMRightsStreamTest(RecvmsgIntoMixin, SCMRightsTest, |
| 5022 |
SendrecvmsgUnixStreamTestBase): |
| 5023 |
pass |
| 5024 |
|
| 5025 |
|
| 5026 |
# Test interrupting the interruptible send/receive methods with a |
| 5027 |
# signal when a timeout is set. These tests avoid having multiple |
| 5028 |
# threads alive during the test so that the OS cannot deliver the |
| 5029 |
# signal to the wrong one. |
| 5030 |
|
| 5031 |
class InterruptedTimeoutBase: |
| 5032 |
# Base class for interrupted send/receive tests. Installs an |
| 5033 |
# empty handler for SIGALRM and removes it on teardown, along with |
| 5034 |
# any scheduled alarms. |
| 5035 |
|
| 5036 |
def setUp(self): |
| 5037 |
super().setUp() |
| 5038 |
orig_alrm_handler = signal.signal(signal.SIGALRM, |
| 5039 |
lambda signum, frame: 1 / 0) |
| 5040 |
self.addCleanup(signal.signal, signal.SIGALRM, orig_alrm_handler) |
| 5041 |
|
| 5042 |
# Timeout for socket operations |
| 5043 |
timeout = support.LOOPBACK_TIMEOUT |
| 5044 |
|
| 5045 |
# Provide setAlarm() method to schedule delivery of SIGALRM after |
| 5046 |
# given number of seconds, or cancel it if zero, and an |
| 5047 |
# appropriate time value to use. Use setitimer() if available. |
| 5048 |
if hasattr(signal, "setitimer"): |
| 5049 |
alarm_time = 0.05 |
| 5050 |
|
| 5051 |
def setAlarm(self, seconds): |
| 5052 |
signal.setitimer(signal.ITIMER_REAL, seconds) |
| 5053 |
else: |
| 5054 |
# Old systems may deliver the alarm up to one second early |
| 5055 |
alarm_time = 2 |
| 5056 |
|
| 5057 |
def setAlarm(self, seconds): |
| 5058 |
signal.alarm(seconds) |
| 5059 |
|
| 5060 |
|
| 5061 |
# Require siginterrupt() in order to ensure that system calls are |
| 5062 |
# interrupted by default. |
| 5063 |
@requireAttrs(signal, "siginterrupt") |
| 5064 |
@unittest.skipUnless(hasattr(signal, "alarm") or hasattr(signal, "setitimer"), |
| 5065 |
"Don't have signal.alarm or signal.setitimer") |
| 5066 |
class InterruptedRecvTimeoutTest(InterruptedTimeoutBase, UDPTestBase): |
| 5067 |
# Test interrupting the recv*() methods with signals when a |
| 5068 |
# timeout is set. |
| 5069 |
|
| 5070 |
def setUp(self): |
| 5071 |
super().setUp() |
| 5072 |
self.serv.settimeout(self.timeout) |
| 5073 |
|
| 5074 |
def checkInterruptedRecv(self, func, *args, **kwargs): |
| 5075 |
# Check that func(*args, **kwargs) raises |
| 5076 |
# errno of EINTR when interrupted by a signal. |
| 5077 |
try: |
| 5078 |
self.setAlarm(self.alarm_time) |
| 5079 |
with self.assertRaises(ZeroDivisionError) as cm: |
| 5080 |
func(*args, **kwargs) |
| 5081 |
finally: |
| 5082 |
self.setAlarm(0) |
| 5083 |
|
| 5084 |
def testInterruptedRecvTimeout(self): |
| 5085 |
self.checkInterruptedRecv(self.serv.recv, 1024) |
| 5086 |
|
| 5087 |
def testInterruptedRecvIntoTimeout(self): |
| 5088 |
self.checkInterruptedRecv(self.serv.recv_into, bytearray(1024)) |
| 5089 |
|
| 5090 |
def testInterruptedRecvfromTimeout(self): |
| 5091 |
self.checkInterruptedRecv(self.serv.recvfrom, 1024) |
| 5092 |
|
| 5093 |
def testInterruptedRecvfromIntoTimeout(self): |
| 5094 |
self.checkInterruptedRecv(self.serv.recvfrom_into, bytearray(1024)) |
| 5095 |
|
| 5096 |
@requireAttrs(socket.socket, "recvmsg") |
| 5097 |
def testInterruptedRecvmsgTimeout(self): |
| 5098 |
self.checkInterruptedRecv(self.serv.recvmsg, 1024) |
| 5099 |
|
| 5100 |
@requireAttrs(socket.socket, "recvmsg_into") |
| 5101 |
def testInterruptedRecvmsgIntoTimeout(self): |
| 5102 |
self.checkInterruptedRecv(self.serv.recvmsg_into, [bytearray(1024)]) |
| 5103 |
|
| 5104 |
|
| 5105 |
# Require siginterrupt() in order to ensure that system calls are |
| 5106 |
# interrupted by default. |
| 5107 |
@requireAttrs(signal, "siginterrupt") |
| 5108 |
@unittest.skipUnless(hasattr(signal, "alarm") or hasattr(signal, "setitimer"), |
| 5109 |
"Don't have signal.alarm or signal.setitimer") |
| 5110 |
class InterruptedSendTimeoutTest(InterruptedTimeoutBase, |
| 5111 |
SocketListeningTestMixin, TCPTestBase): |
| 5112 |
# Test interrupting the interruptible send*() methods with signals |
| 5113 |
# when a timeout is set. |
| 5114 |
|
| 5115 |
def setUp(self): |
| 5116 |
super().setUp() |
| 5117 |
self.serv_conn = self.newSocket() |
| 5118 |
self.addCleanup(self.serv_conn.close) |
| 5119 |
# Use a thread to complete the connection, but wait for it to |
| 5120 |
# terminate before running the test, so that there is only one |
| 5121 |
# thread to accept the signal. |
| 5122 |
cli_thread = threading.Thread(target=self.doConnect) |
| 5123 |
cli_thread.start() |
| 5124 |
self.cli_conn, addr = self.serv.accept() |
| 5125 |
self.addCleanup(self.cli_conn.close) |
| 5126 |
cli_thread.join() |
| 5127 |
self.serv_conn.settimeout(self.timeout) |
| 5128 |
|
| 5129 |
def doConnect(self): |
| 5130 |
self.serv_conn.connect(self.serv_addr) |
| 5131 |
|
| 5132 |
def checkInterruptedSend(self, func, *args, **kwargs): |
| 5133 |
# Check that func(*args, **kwargs), run in a loop, raises |
| 5134 |
# OSError with an errno of EINTR when interrupted by a |
| 5135 |
# signal. |
| 5136 |
try: |
| 5137 |
with self.assertRaises(ZeroDivisionError) as cm: |
| 5138 |
while True: |
| 5139 |
self.setAlarm(self.alarm_time) |
| 5140 |
func(*args, **kwargs) |
| 5141 |
finally: |
| 5142 |
self.setAlarm(0) |
| 5143 |
|
| 5144 |
# Issue #12958: The following tests have problems on OS X prior to 10.7 |
| 5145 |
@support.requires_mac_ver(10, 7) |
| 5146 |
def testInterruptedSendTimeout(self): |
| 5147 |
self.checkInterruptedSend(self.serv_conn.send, b"a"*512) |
| 5148 |
|
| 5149 |
@support.requires_mac_ver(10, 7) |
| 5150 |
def testInterruptedSendtoTimeout(self): |
| 5151 |
# Passing an actual address here as Python's wrapper for |
| 5152 |
# sendto() doesn't allow passing a zero-length one; POSIX |
| 5153 |
# requires that the address is ignored since the socket is |
| 5154 |
# connection-mode, however. |
| 5155 |
self.checkInterruptedSend(self.serv_conn.sendto, b"a"*512, |
| 5156 |
self.serv_addr) |
| 5157 |
|
| 5158 |
@support.requires_mac_ver(10, 7) |
| 5159 |
@requireAttrs(socket.socket, "sendmsg") |
| 5160 |
def testInterruptedSendmsgTimeout(self): |
| 5161 |
self.checkInterruptedSend(self.serv_conn.sendmsg, [b"a"*512]) |
| 5162 |
|
| 5163 |
|
| 5164 |
class TCPCloserTest(ThreadedTCPSocketTest): |
| 5165 |
def testClose(self): |
| 5166 |
conn, _ = self.serv.accept() |
| 5167 |
|
| 5168 |
read, _, _ = select.select([conn], [], [], support.SHORT_TIMEOUT) |
| 5169 |
self.assertEqual(read, [conn]) |
| 5170 |
self.assertEqual(conn.recv(1), b'x') |
| 5171 |
conn.close() |
| 5172 |
|
| 5173 |
# Calling close() many times should be safe. |
| 5174 |
conn.close() |
| 5175 |
conn.close() |
| 5176 |
|
| 5177 |
def _testClose(self): |
| 5178 |
self.cli.connect((HOST, self.port)) |
| 5179 |
self.cli.send(b'x') |
| 5180 |
read, _, _ = select.select([self.cli], [], [], support.SHORT_TIMEOUT) |
| 5181 |
self.assertEqual(read, [self.cli]) |
| 5182 |
self.assertEqual(self.cli.recv(1), b'') |
| 5183 |
|
| 5184 |
|
| 5185 |
class BasicSocketPairTest(SocketPairTest): |
| 5186 |
|
| 5187 |
def __init__(self, methodName='runTest'): |
| 5188 |
SocketPairTest.__init__(self, methodName=methodName) |
| 5189 |
|
| 5190 |
def _check_defaults(self, sock): |
| 5191 |
self.assertIsInstance(sock, socket.socket) |
| 5192 |
if hasattr(socket, 'AF_UNIX'): |
| 5193 |
self.assertEqual(sock.family, socket.AF_UNIX) |
| 5194 |
else: |
| 5195 |
self.assertEqual(sock.family, socket.AF_INET) |
| 5196 |
self.assertEqual(sock.type, socket.SOCK_STREAM) |
| 5197 |
self.assertEqual(sock.proto, 0) |
| 5198 |
|
| 5199 |
def _testDefaults(self): |
| 5200 |
self._check_defaults(self.cli) |
| 5201 |
|
| 5202 |
def testDefaults(self): |
| 5203 |
self._check_defaults(self.serv) |
| 5204 |
|
| 5205 |
def testRecv(self): |
| 5206 |
msg = self.serv.recv(1024) |
| 5207 |
self.assertEqual(msg, MSG) |
| 5208 |
|
| 5209 |
def _testRecv(self): |
| 5210 |
self.cli.send(MSG) |
| 5211 |
|
| 5212 |
def testSend(self): |
| 5213 |
self.serv.send(MSG) |
| 5214 |
|
| 5215 |
def _testSend(self): |
| 5216 |
msg = self.cli.recv(1024) |
| 5217 |
self.assertEqual(msg, MSG) |
| 5218 |
|
| 5219 |
|
| 5220 |
class PurePythonSocketPairTest(SocketPairTest): |
| 5221 |
# Explicitly use socketpair AF_INET or AF_INET6 to ensure that is the |
| 5222 |
# code path we're using regardless platform is the pure python one where |
| 5223 |
# `_socket.socketpair` does not exist. (AF_INET does not work with |
| 5224 |
# _socket.socketpair on many platforms). |
| 5225 |
def socketpair(self): |
| 5226 |
# called by super().setUp(). |
| 5227 |
try: |
| 5228 |
return socket.socketpair(socket.AF_INET6) |
| 5229 |
except OSError: |
| 5230 |
return socket.socketpair(socket.AF_INET) |
| 5231 |
|
| 5232 |
# Local imports in this class make for easy security fix backporting. |
| 5233 |
|
| 5234 |
def setUp(self): |
| 5235 |
if hasattr(_socket, "socketpair"): |
| 5236 |
self._orig_sp = socket.socketpair |
| 5237 |
# This forces the version using the non-OS provided socketpair |
| 5238 |
# emulation via an AF_INET socket in Lib/socket.py. |
| 5239 |
socket.socketpair = socket._fallback_socketpair |
| 5240 |
else: |
| 5241 |
# This platform already uses the non-OS provided version. |
| 5242 |
self._orig_sp = None |
| 5243 |
super().setUp() |
| 5244 |
|
| 5245 |
def tearDown(self): |
| 5246 |
super().tearDown() |
| 5247 |
if self._orig_sp is not None: |
| 5248 |
# Restore the default socket.socketpair definition. |
| 5249 |
socket.socketpair = self._orig_sp |
| 5250 |
|
| 5251 |
def test_recv(self): |
| 5252 |
msg = self.serv.recv(1024) |
| 5253 |
self.assertEqual(msg, MSG) |
| 5254 |
|
| 5255 |
def _test_recv(self): |
| 5256 |
self.cli.send(MSG) |
| 5257 |
|
| 5258 |
def test_send(self): |
| 5259 |
self.serv.send(MSG) |
| 5260 |
|
| 5261 |
def _test_send(self): |
| 5262 |
msg = self.cli.recv(1024) |
| 5263 |
self.assertEqual(msg, MSG) |
| 5264 |
|
| 5265 |
def test_ipv4(self): |
| 5266 |
cli, srv = socket.socketpair(socket.AF_INET) |
| 5267 |
cli.close() |
| 5268 |
srv.close() |
| 5269 |
|
| 5270 |
def _test_ipv4(self): |
| 5271 |
pass |
| 5272 |
|
| 5273 |
@unittest.skipIf(not hasattr(_socket, 'IPPROTO_IPV6') or |
| 5274 |
not hasattr(_socket, 'IPV6_V6ONLY'), |
| 5275 |
"IPV6_V6ONLY option not supported") |
| 5276 |
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test') |
| 5277 |
def test_ipv6(self): |
| 5278 |
cli, srv = socket.socketpair(socket.AF_INET6) |
| 5279 |
cli.close() |
| 5280 |
srv.close() |
| 5281 |
|
| 5282 |
def _test_ipv6(self): |
| 5283 |
pass |
| 5284 |
|
| 5285 |
def test_injected_authentication_failure(self): |
| 5286 |
orig_getsockname = socket.socket.getsockname |
| 5287 |
inject_sock = None |
| 5288 |
|
| 5289 |
def inject_getsocketname(self): |
| 5290 |
nonlocal inject_sock |
| 5291 |
sockname = orig_getsockname(self) |
| 5292 |
# Connect to the listening socket ahead of the |
| 5293 |
# client socket. |
| 5294 |
if inject_sock is None: |
| 5295 |
inject_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 5296 |
inject_sock.setblocking(False) |
| 5297 |
try: |
| 5298 |
inject_sock.connect(sockname[:2]) |
| 5299 |
except (BlockingIOError, InterruptedError): |
| 5300 |
pass |
| 5301 |
inject_sock.setblocking(True) |
| 5302 |
return sockname |
| 5303 |
|
| 5304 |
sock1 = sock2 = None |
| 5305 |
try: |
| 5306 |
socket.socket.getsockname = inject_getsocketname |
| 5307 |
with self.assertRaises(OSError): |
| 5308 |
sock1, sock2 = socket.socketpair() |
| 5309 |
finally: |
| 5310 |
socket.socket.getsockname = orig_getsockname |
| 5311 |
if inject_sock: |
| 5312 |
inject_sock.close() |
| 5313 |
if sock1: # This cleanup isn't needed on a successful test. |
| 5314 |
sock1.close() |
| 5315 |
if sock2: |
| 5316 |
sock2.close() |
| 5317 |
|
| 5318 |
def _test_injected_authentication_failure(self): |
| 5319 |
# No-op. Exists for base class threading infrastructure to call. |
| 5320 |
# We could refactor this test into its own lesser class along with the |
| 5321 |
# setUp and tearDown code to construct an ideal; it is simpler to keep |
| 5322 |
# it here and live with extra overhead one this _one_ failure test. |
| 5323 |
pass |
| 5324 |
|
| 5325 |
|
| 5326 |
class NonBlockingTCPTests(ThreadedTCPSocketTest): |
| 5327 |
|
| 5328 |
def __init__(self, methodName='runTest'): |
| 5329 |
self.event = threading.Event() |
| 5330 |
ThreadedTCPSocketTest.__init__(self, methodName=methodName) |
| 5331 |
|
| 5332 |
def assert_sock_timeout(self, sock, timeout): |
| 5333 |
self.assertEqual(self.serv.gettimeout(), timeout) |
| 5334 |
|
| 5335 |
blocking = (timeout != 0.0) |
| 5336 |
self.assertEqual(sock.getblocking(), blocking) |
| 5337 |
|
| 5338 |
if fcntl is not None: |
| 5339 |
# When a Python socket has a non-zero timeout, it's switched |
| 5340 |
# internally to a non-blocking mode. Later, sock.sendall(), |
| 5341 |
# sock.recv(), and other socket operations use a select() call and |
| 5342 |
# handle EWOULDBLOCK/EGAIN on all socket operations. That's how |
| 5343 |
# timeouts are enforced. |
| 5344 |
fd_blocking = (timeout is None) |
| 5345 |
|
| 5346 |
flag = fcntl.fcntl(sock, fcntl.F_GETFL, os.O_NONBLOCK) |
| 5347 |
self.assertEqual(not bool(flag & os.O_NONBLOCK), fd_blocking) |
| 5348 |
|
| 5349 |
def testSetBlocking(self): |
| 5350 |
# Test setblocking() and settimeout() methods |
| 5351 |
self.serv.setblocking(True) |
| 5352 |
self.assert_sock_timeout(self.serv, None) |
| 5353 |
|
| 5354 |
self.serv.setblocking(False) |
| 5355 |
self.assert_sock_timeout(self.serv, 0.0) |
| 5356 |
|
| 5357 |
self.serv.settimeout(None) |
| 5358 |
self.assert_sock_timeout(self.serv, None) |
| 5359 |
|
| 5360 |
self.serv.settimeout(0) |
| 5361 |
self.assert_sock_timeout(self.serv, 0) |
| 5362 |
|
| 5363 |
self.serv.settimeout(10) |
| 5364 |
self.assert_sock_timeout(self.serv, 10) |
| 5365 |
|
| 5366 |
self.serv.settimeout(0) |
| 5367 |
self.assert_sock_timeout(self.serv, 0) |
| 5368 |
|
| 5369 |
def _testSetBlocking(self): |
| 5370 |
pass |
| 5371 |
|
| 5372 |
@support.cpython_only |
| 5373 |
@unittest.skipIf(_testcapi is None, "requires _testcapi") |
| 5374 |
def testSetBlocking_overflow(self): |
| 5375 |
# Issue 15989 |
| 5376 |
import _testcapi |
| 5377 |
if _testcapi.UINT_MAX >= _testcapi.ULONG_MAX: |
| 5378 |
self.skipTest('needs UINT_MAX < ULONG_MAX') |
| 5379 |
|
| 5380 |
self.serv.setblocking(False) |
| 5381 |
self.assertEqual(self.serv.gettimeout(), 0.0) |
| 5382 |
|
| 5383 |
self.serv.setblocking(_testcapi.UINT_MAX + 1) |
| 5384 |
self.assertIsNone(self.serv.gettimeout()) |
| 5385 |
|
| 5386 |
_testSetBlocking_overflow = support.cpython_only(_testSetBlocking) |
| 5387 |
|
| 5388 |
@unittest.skipUnless(hasattr(socket, 'SOCK_NONBLOCK'), |
| 5389 |
'test needs socket.SOCK_NONBLOCK') |
| 5390 |
@support.requires_linux_version(2, 6, 28) |
| 5391 |
def testInitNonBlocking(self): |
| 5392 |
# create a socket with SOCK_NONBLOCK |
| 5393 |
self.serv.close() |
| 5394 |
self.serv = socket.socket(socket.AF_INET, |
| 5395 |
socket.SOCK_STREAM | socket.SOCK_NONBLOCK) |
| 5396 |
self.assert_sock_timeout(self.serv, 0) |
| 5397 |
|
| 5398 |
def _testInitNonBlocking(self): |
| 5399 |
pass |
| 5400 |
|
| 5401 |
def testInheritFlagsBlocking(self): |
| 5402 |
# bpo-7995: accept() on a listening socket with a timeout and the |
| 5403 |
# default timeout is None, the resulting socket must be blocking. |
| 5404 |
with socket_setdefaulttimeout(None): |
| 5405 |
self.serv.settimeout(10) |
| 5406 |
conn, addr = self.serv.accept() |
| 5407 |
self.addCleanup(conn.close) |
| 5408 |
self.assertIsNone(conn.gettimeout()) |
| 5409 |
|
| 5410 |
def _testInheritFlagsBlocking(self): |
| 5411 |
self.cli.connect((HOST, self.port)) |
| 5412 |
|
| 5413 |
def testInheritFlagsTimeout(self): |
| 5414 |
# bpo-7995: accept() on a listening socket with a timeout and the |
| 5415 |
# default timeout is None, the resulting socket must inherit |
| 5416 |
# the default timeout. |
| 5417 |
default_timeout = 20.0 |
| 5418 |
with socket_setdefaulttimeout(default_timeout): |
| 5419 |
self.serv.settimeout(10) |
| 5420 |
conn, addr = self.serv.accept() |
| 5421 |
self.addCleanup(conn.close) |
| 5422 |
self.assertEqual(conn.gettimeout(), default_timeout) |
| 5423 |
|
| 5424 |
def _testInheritFlagsTimeout(self): |
| 5425 |
self.cli.connect((HOST, self.port)) |
| 5426 |
|
| 5427 |
def testAccept(self): |
| 5428 |
# Testing non-blocking accept |
| 5429 |
self.serv.setblocking(False) |
| 5430 |
|
| 5431 |
# connect() didn't start: non-blocking accept() fails |
| 5432 |
start_time = time.monotonic() |
| 5433 |
with self.assertRaises(BlockingIOError): |
| 5434 |
conn, addr = self.serv.accept() |
| 5435 |
dt = time.monotonic() - start_time |
| 5436 |
self.assertLess(dt, 1.0) |
| 5437 |
|
| 5438 |
self.event.set() |
| 5439 |
|
| 5440 |
read, write, err = select.select([self.serv], [], [], support.LONG_TIMEOUT) |
| 5441 |
if self.serv not in read: |
| 5442 |
self.fail("Error trying to do accept after select.") |
| 5443 |
|
| 5444 |
# connect() completed: non-blocking accept() doesn't block |
| 5445 |
conn, addr = self.serv.accept() |
| 5446 |
self.addCleanup(conn.close) |
| 5447 |
self.assertIsNone(conn.gettimeout()) |
| 5448 |
|
| 5449 |
def _testAccept(self): |
| 5450 |
# don't connect before event is set to check |
| 5451 |
# that non-blocking accept() raises BlockingIOError |
| 5452 |
self.event.wait() |
| 5453 |
|
| 5454 |
self.cli.connect((HOST, self.port)) |
| 5455 |
|
| 5456 |
def testRecv(self): |
| 5457 |
# Testing non-blocking recv |
| 5458 |
conn, addr = self.serv.accept() |
| 5459 |
self.addCleanup(conn.close) |
| 5460 |
conn.setblocking(False) |
| 5461 |
|
| 5462 |
# the server didn't send data yet: non-blocking recv() fails |
| 5463 |
with self.assertRaises(BlockingIOError): |
| 5464 |
msg = conn.recv(len(MSG)) |
| 5465 |
|
| 5466 |
self.event.set() |
| 5467 |
|
| 5468 |
read, write, err = select.select([conn], [], [], support.LONG_TIMEOUT) |
| 5469 |
if conn not in read: |
| 5470 |
self.fail("Error during select call to non-blocking socket.") |
| 5471 |
|
| 5472 |
# the server sent data yet: non-blocking recv() doesn't block |
| 5473 |
msg = conn.recv(len(MSG)) |
| 5474 |
self.assertEqual(msg, MSG) |
| 5475 |
|
| 5476 |
def _testRecv(self): |
| 5477 |
self.cli.connect((HOST, self.port)) |
| 5478 |
|
| 5479 |
# don't send anything before event is set to check |
| 5480 |
# that non-blocking recv() raises BlockingIOError |
| 5481 |
self.event.wait() |
| 5482 |
|
| 5483 |
# send data: recv() will no longer block |
| 5484 |
self.cli.sendall(MSG) |
| 5485 |
|
| 5486 |
def testLargeTimeout(self): |
| 5487 |
# gh-126876: Check that a timeout larger than INT_MAX is replaced with |
| 5488 |
# INT_MAX in the poll() code path. The following assertion must not |
| 5489 |
# fail: assert(INT_MIN <= ms && ms <= INT_MAX). |
| 5490 |
if _testcapi is not None: |
| 5491 |
large_timeout = _testcapi.INT_MAX + 1 |
| 5492 |
else: |
| 5493 |
large_timeout = 2147483648 |
| 5494 |
|
| 5495 |
# test recv() with large timeout |
| 5496 |
conn, addr = self.serv.accept() |
| 5497 |
self.addCleanup(conn.close) |
| 5498 |
try: |
| 5499 |
conn.settimeout(large_timeout) |
| 5500 |
except OverflowError: |
| 5501 |
# On Windows, settimeout() fails with OverflowError, whereas |
| 5502 |
# we want to test recv(). Just give up silently. |
| 5503 |
return |
| 5504 |
msg = conn.recv(len(MSG)) |
| 5505 |
|
| 5506 |
def _testLargeTimeout(self): |
| 5507 |
# test sendall() with large timeout |
| 5508 |
if _testcapi is not None: |
| 5509 |
large_timeout = _testcapi.INT_MAX + 1 |
| 5510 |
else: |
| 5511 |
large_timeout = 2147483648 |
| 5512 |
self.cli.connect((HOST, self.port)) |
| 5513 |
try: |
| 5514 |
self.cli.settimeout(large_timeout) |
| 5515 |
except OverflowError: |
| 5516 |
return |
| 5517 |
self.cli.sendall(MSG) |
| 5518 |
|
| 5519 |
|
| 5520 |
class FileObjectClassTestCase(SocketConnectedTest): |
| 5521 |
"""Unit tests for the object returned by socket.makefile() |
| 5522 |
|
| 5523 |
self.read_file is the io object returned by makefile() on |
| 5524 |
the client connection. You can read from this file to |
| 5525 |
get output from the server. |
| 5526 |
|
| 5527 |
self.write_file is the io object returned by makefile() on the |
| 5528 |
server connection. You can write to this file to send output |
| 5529 |
to the client. |
| 5530 |
""" |
| 5531 |
|
| 5532 |
bufsize = -1 # Use default buffer size |
| 5533 |
encoding = 'utf-8' |
| 5534 |
errors = 'strict' |
| 5535 |
newline = None |
| 5536 |
|
| 5537 |
read_mode = 'rb' |
| 5538 |
read_msg = MSG |
| 5539 |
write_mode = 'wb' |
| 5540 |
write_msg = MSG |
| 5541 |
|
| 5542 |
def __init__(self, methodName='runTest'): |
| 5543 |
SocketConnectedTest.__init__(self, methodName=methodName) |
| 5544 |
|
| 5545 |
def setUp(self): |
| 5546 |
self.evt1, self.evt2, self.serv_finished, self.cli_finished = [ |
| 5547 |
threading.Event() for i in range(4)] |
| 5548 |
SocketConnectedTest.setUp(self) |
| 5549 |
self.read_file = self.cli_conn.makefile( |
| 5550 |
self.read_mode, self.bufsize, |
| 5551 |
encoding = self.encoding, |
| 5552 |
errors = self.errors, |
| 5553 |
newline = self.newline) |
| 5554 |
|
| 5555 |
def tearDown(self): |
| 5556 |
self.serv_finished.set() |
| 5557 |
self.read_file.close() |
| 5558 |
self.assertTrue(self.read_file.closed) |
| 5559 |
self.read_file = None |
| 5560 |
SocketConnectedTest.tearDown(self) |
| 5561 |
|
| 5562 |
def clientSetUp(self): |
| 5563 |
SocketConnectedTest.clientSetUp(self) |
| 5564 |
self.write_file = self.serv_conn.makefile( |
| 5565 |
self.write_mode, self.bufsize, |
| 5566 |
encoding = self.encoding, |
| 5567 |
errors = self.errors, |
| 5568 |
newline = self.newline) |
| 5569 |
|
| 5570 |
def clientTearDown(self): |
| 5571 |
self.cli_finished.set() |
| 5572 |
self.write_file.close() |
| 5573 |
self.assertTrue(self.write_file.closed) |
| 5574 |
self.write_file = None |
| 5575 |
SocketConnectedTest.clientTearDown(self) |
| 5576 |
|
| 5577 |
def testReadAfterTimeout(self): |
| 5578 |
# Issue #7322: A file object must disallow further reads |
| 5579 |
# after a timeout has occurred. |
| 5580 |
self.cli_conn.settimeout(1) |
| 5581 |
self.read_file.read(3) |
| 5582 |
# First read raises a timeout |
| 5583 |
self.assertRaises(TimeoutError, self.read_file.read, 1) |
| 5584 |
# Second read is disallowed |
| 5585 |
with self.assertRaises(OSError) as ctx: |
| 5586 |
self.read_file.read(1) |
| 5587 |
self.assertIn("cannot read from timed out object", str(ctx.exception)) |
| 5588 |
|
| 5589 |
def _testReadAfterTimeout(self): |
| 5590 |
self.write_file.write(self.write_msg[0:3]) |
| 5591 |
self.write_file.flush() |
| 5592 |
self.serv_finished.wait() |
| 5593 |
|
| 5594 |
def testSmallRead(self): |
| 5595 |
# Performing small file read test |
| 5596 |
first_seg = self.read_file.read(len(self.read_msg)-3) |
| 5597 |
second_seg = self.read_file.read(3) |
| 5598 |
msg = first_seg + second_seg |
| 5599 |
self.assertEqual(msg, self.read_msg) |
| 5600 |
|
| 5601 |
def _testSmallRead(self): |
| 5602 |
self.write_file.write(self.write_msg) |
| 5603 |
self.write_file.flush() |
| 5604 |
|
| 5605 |
def testFullRead(self): |
| 5606 |
# read until EOF |
| 5607 |
msg = self.read_file.read() |
| 5608 |
self.assertEqual(msg, self.read_msg) |
| 5609 |
|
| 5610 |
def _testFullRead(self): |
| 5611 |
self.write_file.write(self.write_msg) |
| 5612 |
self.write_file.close() |
| 5613 |
|
| 5614 |
def testUnbufferedRead(self): |
| 5615 |
# Performing unbuffered file read test |
| 5616 |
buf = type(self.read_msg)() |
| 5617 |
while 1: |
| 5618 |
char = self.read_file.read(1) |
| 5619 |
if not char: |
| 5620 |
break |
| 5621 |
buf += char |
| 5622 |
self.assertEqual(buf, self.read_msg) |
| 5623 |
|
| 5624 |
def _testUnbufferedRead(self): |
| 5625 |
self.write_file.write(self.write_msg) |
| 5626 |
self.write_file.flush() |
| 5627 |
|
| 5628 |
def testReadline(self): |
| 5629 |
# Performing file readline test |
| 5630 |
line = self.read_file.readline() |
| 5631 |
self.assertEqual(line, self.read_msg) |
| 5632 |
|
| 5633 |
def _testReadline(self): |
| 5634 |
self.write_file.write(self.write_msg) |
| 5635 |
self.write_file.flush() |
| 5636 |
|
| 5637 |
def testCloseAfterMakefile(self): |
| 5638 |
# The file returned by makefile should keep the socket open. |
| 5639 |
self.cli_conn.close() |
| 5640 |
# read until EOF |
| 5641 |
msg = self.read_file.read() |
| 5642 |
self.assertEqual(msg, self.read_msg) |
| 5643 |
|
| 5644 |
def _testCloseAfterMakefile(self): |
| 5645 |
self.write_file.write(self.write_msg) |
| 5646 |
self.write_file.flush() |
| 5647 |
|
| 5648 |
def testMakefileAfterMakefileClose(self): |
| 5649 |
self.read_file.close() |
| 5650 |
msg = self.cli_conn.recv(len(MSG)) |
| 5651 |
if isinstance(self.read_msg, str): |
| 5652 |
msg = msg.decode() |
| 5653 |
self.assertEqual(msg, self.read_msg) |
| 5654 |
|
| 5655 |
def _testMakefileAfterMakefileClose(self): |
| 5656 |
self.write_file.write(self.write_msg) |
| 5657 |
self.write_file.flush() |
| 5658 |
|
| 5659 |
def testClosedAttr(self): |
| 5660 |
self.assertTrue(not self.read_file.closed) |
| 5661 |
|
| 5662 |
def _testClosedAttr(self): |
| 5663 |
self.assertTrue(not self.write_file.closed) |
| 5664 |
|
| 5665 |
def testAttributes(self): |
| 5666 |
self.assertEqual(self.read_file.mode, self.read_mode) |
| 5667 |
self.assertEqual(self.read_file.name, self.cli_conn.fileno()) |
| 5668 |
|
| 5669 |
def _testAttributes(self): |
| 5670 |
self.assertEqual(self.write_file.mode, self.write_mode) |
| 5671 |
self.assertEqual(self.write_file.name, self.serv_conn.fileno()) |
| 5672 |
|
| 5673 |
def testRealClose(self): |
| 5674 |
self.read_file.close() |
| 5675 |
self.assertRaises(ValueError, self.read_file.fileno) |
| 5676 |
self.cli_conn.close() |
| 5677 |
self.assertRaises(OSError, self.cli_conn.getsockname) |
| 5678 |
|
| 5679 |
def _testRealClose(self): |
| 5680 |
pass |
| 5681 |
|
| 5682 |
|
| 5683 |
class UnbufferedFileObjectClassTestCase(FileObjectClassTestCase): |
| 5684 |
|
| 5685 |
"""Repeat the tests from FileObjectClassTestCase with bufsize==0. |
| 5686 |
|
| 5687 |
In this case (and in this case only), it should be possible to |
| 5688 |
create a file object, read a line from it, create another file |
| 5689 |
object, read another line from it, without loss of data in the |
| 5690 |
first file object's buffer. Note that http.client relies on this |
| 5691 |
when reading multiple requests from the same socket.""" |
| 5692 |
|
| 5693 |
bufsize = 0 # Use unbuffered mode |
| 5694 |
|
| 5695 |
def testUnbufferedReadline(self): |
| 5696 |
# Read a line, create a new file object, read another line with it |
| 5697 |
line = self.read_file.readline() # first line |
| 5698 |
self.assertEqual(line, b"A. " + self.write_msg) # first line |
| 5699 |
self.read_file = self.cli_conn.makefile('rb', 0) |
| 5700 |
line = self.read_file.readline() # second line |
| 5701 |
self.assertEqual(line, b"B. " + self.write_msg) # second line |
| 5702 |
|
| 5703 |
def _testUnbufferedReadline(self): |
| 5704 |
self.write_file.write(b"A. " + self.write_msg) |
| 5705 |
self.write_file.write(b"B. " + self.write_msg) |
| 5706 |
self.write_file.flush() |
| 5707 |
|
| 5708 |
def testMakefileClose(self): |
| 5709 |
# The file returned by makefile should keep the socket open... |
| 5710 |
self.cli_conn.close() |
| 5711 |
msg = self.cli_conn.recv(1024) |
| 5712 |
self.assertEqual(msg, self.read_msg) |
| 5713 |
# ...until the file is itself closed |
| 5714 |
self.read_file.close() |
| 5715 |
self.assertRaises(OSError, self.cli_conn.recv, 1024) |
| 5716 |
|
| 5717 |
def _testMakefileClose(self): |
| 5718 |
self.write_file.write(self.write_msg) |
| 5719 |
self.write_file.flush() |
| 5720 |
|
| 5721 |
@unittest.skipUnless(hasattr(sys, 'getrefcount'), |
| 5722 |
'test needs sys.getrefcount()') |
| 5723 |
def testMakefileCloseSocketDestroy(self): |
| 5724 |
refcount_before = sys.getrefcount(self.cli_conn) |
| 5725 |
self.read_file.close() |
| 5726 |
refcount_after = sys.getrefcount(self.cli_conn) |
| 5727 |
self.assertEqual(refcount_before - 1, refcount_after) |
| 5728 |
|
| 5729 |
def _testMakefileCloseSocketDestroy(self): |
| 5730 |
pass |
| 5731 |
|
| 5732 |
# Non-blocking ops |
| 5733 |
# NOTE: to set `read_file` as non-blocking, we must call |
| 5734 |
# `cli_conn.setblocking` and vice-versa (see setUp / clientSetUp). |
| 5735 |
|
| 5736 |
def testSmallReadNonBlocking(self): |
| 5737 |
self.cli_conn.setblocking(False) |
| 5738 |
self.assertEqual(self.read_file.readinto(bytearray(10)), None) |
| 5739 |
self.assertEqual(self.read_file.read(len(self.read_msg) - 3), None) |
| 5740 |
self.evt1.set() |
| 5741 |
self.evt2.wait(1.0) |
| 5742 |
first_seg = self.read_file.read(len(self.read_msg) - 3) |
| 5743 |
if first_seg is None: |
| 5744 |
# Data not arrived (can happen under Windows), wait a bit |
| 5745 |
time.sleep(0.5) |
| 5746 |
first_seg = self.read_file.read(len(self.read_msg) - 3) |
| 5747 |
buf = bytearray(10) |
| 5748 |
n = self.read_file.readinto(buf) |
| 5749 |
self.assertEqual(n, 3) |
| 5750 |
msg = first_seg + buf[:n] |
| 5751 |
self.assertEqual(msg, self.read_msg) |
| 5752 |
self.assertEqual(self.read_file.readinto(bytearray(16)), None) |
| 5753 |
self.assertEqual(self.read_file.read(1), None) |
| 5754 |
|
| 5755 |
def _testSmallReadNonBlocking(self): |
| 5756 |
self.evt1.wait(1.0) |
| 5757 |
self.write_file.write(self.write_msg) |
| 5758 |
self.write_file.flush() |
| 5759 |
self.evt2.set() |
| 5760 |
# Avoid closing the socket before the server test has finished, |
| 5761 |
# otherwise system recv() will return 0 instead of EWOULDBLOCK. |
| 5762 |
self.serv_finished.wait(5.0) |
| 5763 |
|
| 5764 |
def testWriteNonBlocking(self): |
| 5765 |
self.cli_finished.wait(5.0) |
| 5766 |
# The client thread can't skip directly - the SkipTest exception |
| 5767 |
# would appear as a failure. |
| 5768 |
if self.serv_skipped: |
| 5769 |
self.skipTest(self.serv_skipped) |
| 5770 |
|
| 5771 |
def _testWriteNonBlocking(self): |
| 5772 |
self.serv_skipped = None |
| 5773 |
self.serv_conn.setblocking(False) |
| 5774 |
# Try to saturate the socket buffer pipe with repeated large writes. |
| 5775 |
BIG = b"x" * support.SOCK_MAX_SIZE |
| 5776 |
LIMIT = 10 |
| 5777 |
# The first write() succeeds since a chunk of data can be buffered |
| 5778 |
n = self.write_file.write(BIG) |
| 5779 |
self.assertGreater(n, 0) |
| 5780 |
for i in range(LIMIT): |
| 5781 |
n = self.write_file.write(BIG) |
| 5782 |
if n is None: |
| 5783 |
# Succeeded |
| 5784 |
break |
| 5785 |
self.assertGreater(n, 0) |
| 5786 |
else: |
| 5787 |
# Let us know that this test didn't manage to establish |
| 5788 |
# the expected conditions. This is not a failure in itself but, |
| 5789 |
# if it happens repeatedly, the test should be fixed. |
| 5790 |
self.serv_skipped = "failed to saturate the socket buffer" |
| 5791 |
|
| 5792 |
|
| 5793 |
class LineBufferedFileObjectClassTestCase(FileObjectClassTestCase): |
| 5794 |
|
| 5795 |
bufsize = 1 # Default-buffered for reading; line-buffered for writing |
| 5796 |
|
| 5797 |
|
| 5798 |
class SmallBufferedFileObjectClassTestCase(FileObjectClassTestCase): |
| 5799 |
|
| 5800 |
bufsize = 2 # Exercise the buffering code |
| 5801 |
|
| 5802 |
|
| 5803 |
class UnicodeReadFileObjectClassTestCase(FileObjectClassTestCase): |
| 5804 |
"""Tests for socket.makefile() in text mode (rather than binary)""" |
| 5805 |
|
| 5806 |
read_mode = 'r' |
| 5807 |
read_msg = MSG.decode('utf-8') |
| 5808 |
write_mode = 'wb' |
| 5809 |
write_msg = MSG |
| 5810 |
newline = '' |
| 5811 |
|
| 5812 |
|
| 5813 |
class UnicodeWriteFileObjectClassTestCase(FileObjectClassTestCase): |
| 5814 |
"""Tests for socket.makefile() in text mode (rather than binary)""" |
| 5815 |
|
| 5816 |
read_mode = 'rb' |
| 5817 |
read_msg = MSG |
| 5818 |
write_mode = 'w' |
| 5819 |
write_msg = MSG.decode('utf-8') |
| 5820 |
newline = '' |
| 5821 |
|
| 5822 |
|
| 5823 |
class UnicodeReadWriteFileObjectClassTestCase(FileObjectClassTestCase): |
| 5824 |
"""Tests for socket.makefile() in text mode (rather than binary)""" |
| 5825 |
|
| 5826 |
read_mode = 'r' |
| 5827 |
read_msg = MSG.decode('utf-8') |
| 5828 |
write_mode = 'w' |
| 5829 |
write_msg = MSG.decode('utf-8') |
| 5830 |
newline = '' |
| 5831 |
|
| 5832 |
|
| 5833 |
class NetworkConnectionTest(object): |
| 5834 |
"""Prove network connection.""" |
| 5835 |
|
| 5836 |
def clientSetUp(self): |
| 5837 |
# We're inherited below by BasicTCPTest2, which also inherits |
| 5838 |
# BasicTCPTest, which defines self.port referenced below. |
| 5839 |
self.cli = socket.create_connection((HOST, self.port)) |
| 5840 |
self.serv_conn = self.cli |
| 5841 |
|
| 5842 |
class BasicTCPTest2(NetworkConnectionTest, BasicTCPTest): |
| 5843 |
"""Tests that NetworkConnection does not break existing TCP functionality. |
| 5844 |
""" |
| 5845 |
|
| 5846 |
class NetworkConnectionNoServer(unittest.TestCase): |
| 5847 |
|
| 5848 |
class MockSocket(socket.socket): |
| 5849 |
def connect(self, *args): |
| 5850 |
raise TimeoutError('timed out') |
| 5851 |
|
| 5852 |
@contextlib.contextmanager |
| 5853 |
def mocked_socket_module(self): |
| 5854 |
"""Return a socket which times out on connect""" |
| 5855 |
old_socket = socket.socket |
| 5856 |
socket.socket = self.MockSocket |
| 5857 |
try: |
| 5858 |
yield |
| 5859 |
finally: |
| 5860 |
socket.socket = old_socket |
| 5861 |
|
| 5862 |
@socket_helper.skip_if_tcp_blackhole |
| 5863 |
def test_connect(self): |
| 5864 |
port = socket_helper.find_unused_port() |
| 5865 |
cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 5866 |
self.addCleanup(cli.close) |
| 5867 |
with self.assertRaises(OSError) as cm: |
| 5868 |
cli.connect((HOST, port)) |
| 5869 |
self.assertEqual(cm.exception.errno, errno.ECONNREFUSED) |
| 5870 |
|
| 5871 |
@socket_helper.skip_if_tcp_blackhole |
| 5872 |
def test_create_connection(self): |
| 5873 |
# Issue #9792: errors raised by create_connection() should have |
| 5874 |
# a proper errno attribute. |
| 5875 |
port = socket_helper.find_unused_port() |
| 5876 |
with self.assertRaises(OSError) as cm: |
| 5877 |
socket.create_connection((HOST, port)) |
| 5878 |
|
| 5879 |
# Issue #16257: create_connection() calls getaddrinfo() against |
| 5880 |
# 'localhost'. This may result in an IPV6 addr being returned |
| 5881 |
# as well as an IPV4 one: |
| 5882 |
# >>> socket.getaddrinfo('localhost', port, 0, SOCK_STREAM) |
| 5883 |
# >>> [(2, 2, 0, '', ('127.0.0.1', 41230)), |
| 5884 |
# (26, 2, 0, '', ('::1', 41230, 0, 0))] |
| 5885 |
# |
| 5886 |
# create_connection() enumerates through all the addresses returned |
| 5887 |
# and if it doesn't successfully bind to any of them, it propagates |
| 5888 |
# the last exception it encountered. |
| 5889 |
# |
| 5890 |
# On Solaris, ENETUNREACH is returned in this circumstance instead |
| 5891 |
# of ECONNREFUSED. So, if that errno exists, add it to our list of |
| 5892 |
# expected errnos. |
| 5893 |
expected_errnos = socket_helper.get_socket_conn_refused_errs() |
| 5894 |
self.assertIn(cm.exception.errno, expected_errnos) |
| 5895 |
|
| 5896 |
def test_create_connection_all_errors(self): |
| 5897 |
port = socket_helper.find_unused_port() |
| 5898 |
try: |
| 5899 |
socket.create_connection((HOST, port), all_errors=True) |
| 5900 |
except ExceptionGroup as e: |
| 5901 |
eg = e |
| 5902 |
else: |
| 5903 |
self.fail('expected connection to fail') |
| 5904 |
|
| 5905 |
self.assertIsInstance(eg, ExceptionGroup) |
| 5906 |
for e in eg.exceptions: |
| 5907 |
self.assertIsInstance(e, OSError) |
| 5908 |
|
| 5909 |
addresses = socket.getaddrinfo( |
| 5910 |
'localhost', port, 0, socket.SOCK_STREAM) |
| 5911 |
# assert that we got an exception for each address |
| 5912 |
self.assertEqual(len(addresses), len(eg.exceptions)) |
| 5913 |
|
| 5914 |
def test_create_connection_timeout(self): |
| 5915 |
# Issue #9792: create_connection() should not recast timeout errors |
| 5916 |
# as generic socket errors. |
| 5917 |
with self.mocked_socket_module(): |
| 5918 |
try: |
| 5919 |
socket.create_connection((HOST, 1234)) |
| 5920 |
except TimeoutError: |
| 5921 |
pass |
| 5922 |
except OSError as exc: |
| 5923 |
if socket_helper.IPV6_ENABLED or exc.errno != errno.EAFNOSUPPORT: |
| 5924 |
raise |
| 5925 |
else: |
| 5926 |
self.fail('TimeoutError not raised') |
| 5927 |
|
| 5928 |
|
| 5929 |
class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest): |
| 5930 |
cli = None |
| 5931 |
|
| 5932 |
def __init__(self, methodName='runTest'): |
| 5933 |
SocketTCPTest.__init__(self, methodName=methodName) |
| 5934 |
ThreadableTest.__init__(self) |
| 5935 |
|
| 5936 |
def clientSetUp(self): |
| 5937 |
self.source_port = socket_helper.find_unused_port() |
| 5938 |
|
| 5939 |
def clientTearDown(self): |
| 5940 |
if self.cli is not None: |
| 5941 |
self.cli.close() |
| 5942 |
self.cli = None |
| 5943 |
ThreadableTest.clientTearDown(self) |
| 5944 |
|
| 5945 |
def _justAccept(self): |
| 5946 |
conn, addr = self.serv.accept() |
| 5947 |
conn.close() |
| 5948 |
|
| 5949 |
testFamily = _justAccept |
| 5950 |
def _testFamily(self): |
| 5951 |
self.cli = socket.create_connection((HOST, self.port), |
| 5952 |
timeout=support.LOOPBACK_TIMEOUT) |
| 5953 |
self.addCleanup(self.cli.close) |
| 5954 |
self.assertEqual(self.cli.family, 2) |
| 5955 |
|
| 5956 |
testSourceAddress = _justAccept |
| 5957 |
def _testSourceAddress(self): |
| 5958 |
self.cli = socket.create_connection((HOST, self.port), |
| 5959 |
timeout=support.LOOPBACK_TIMEOUT, |
| 5960 |
source_address=('', self.source_port)) |
| 5961 |
self.addCleanup(self.cli.close) |
| 5962 |
self.assertEqual(self.cli.getsockname()[1], self.source_port) |
| 5963 |
# The port number being used is sufficient to show that the bind() |
| 5964 |
# call happened. |
| 5965 |
|
| 5966 |
testTimeoutDefault = _justAccept |
| 5967 |
def _testTimeoutDefault(self): |
| 5968 |
# passing no explicit timeout uses socket's global default |
| 5969 |
self.assertTrue(socket.getdefaulttimeout() is None) |
| 5970 |
socket.setdefaulttimeout(42) |
| 5971 |
try: |
| 5972 |
self.cli = socket.create_connection((HOST, self.port)) |
| 5973 |
self.addCleanup(self.cli.close) |
| 5974 |
finally: |
| 5975 |
socket.setdefaulttimeout(None) |
| 5976 |
self.assertEqual(self.cli.gettimeout(), 42) |
| 5977 |
|
| 5978 |
testTimeoutNone = _justAccept |
| 5979 |
def _testTimeoutNone(self): |
| 5980 |
# None timeout means the same as sock.settimeout(None) |
| 5981 |
self.assertTrue(socket.getdefaulttimeout() is None) |
| 5982 |
socket.setdefaulttimeout(30) |
| 5983 |
try: |
| 5984 |
self.cli = socket.create_connection((HOST, self.port), timeout=None) |
| 5985 |
self.addCleanup(self.cli.close) |
| 5986 |
finally: |
| 5987 |
socket.setdefaulttimeout(None) |
| 5988 |
self.assertEqual(self.cli.gettimeout(), None) |
| 5989 |
|
| 5990 |
testTimeoutValueNamed = _justAccept |
| 5991 |
def _testTimeoutValueNamed(self): |
| 5992 |
self.cli = socket.create_connection((HOST, self.port), timeout=30) |
| 5993 |
self.assertEqual(self.cli.gettimeout(), 30) |
| 5994 |
|
| 5995 |
testTimeoutValueNonamed = _justAccept |
| 5996 |
def _testTimeoutValueNonamed(self): |
| 5997 |
self.cli = socket.create_connection((HOST, self.port), 30) |
| 5998 |
self.addCleanup(self.cli.close) |
| 5999 |
self.assertEqual(self.cli.gettimeout(), 30) |
| 6000 |
|
| 6001 |
|
| 6002 |
class NetworkConnectionBehaviourTest(SocketTCPTest, ThreadableTest): |
| 6003 |
|
| 6004 |
def __init__(self, methodName='runTest'): |
| 6005 |
SocketTCPTest.__init__(self, methodName=methodName) |
| 6006 |
ThreadableTest.__init__(self) |
| 6007 |
|
| 6008 |
def clientSetUp(self): |
| 6009 |
pass |
| 6010 |
|
| 6011 |
def clientTearDown(self): |
| 6012 |
self.cli.close() |
| 6013 |
self.cli = None |
| 6014 |
ThreadableTest.clientTearDown(self) |
| 6015 |
|
| 6016 |
def testInsideTimeout(self): |
| 6017 |
conn, addr = self.serv.accept() |
| 6018 |
self.addCleanup(conn.close) |
| 6019 |
time.sleep(3) |
| 6020 |
conn.send(b"done!") |
| 6021 |
testOutsideTimeout = testInsideTimeout |
| 6022 |
|
| 6023 |
def _testInsideTimeout(self): |
| 6024 |
self.cli = sock = socket.create_connection((HOST, self.port)) |
| 6025 |
data = sock.recv(5) |
| 6026 |
self.assertEqual(data, b"done!") |
| 6027 |
|
| 6028 |
def _testOutsideTimeout(self): |
| 6029 |
self.cli = sock = socket.create_connection((HOST, self.port), timeout=1) |
| 6030 |
self.assertRaises(TimeoutError, lambda: sock.recv(5)) |
| 6031 |
|
| 6032 |
|
| 6033 |
class TCPTimeoutTest(SocketTCPTest): |
| 6034 |
|
| 6035 |
def testTCPTimeout(self): |
| 6036 |
def raise_timeout(*args, **kwargs): |
| 6037 |
self.serv.settimeout(1.0) |
| 6038 |
self.serv.accept() |
| 6039 |
self.assertRaises(TimeoutError, raise_timeout, |
| 6040 |
"Error generating a timeout exception (TCP)") |
| 6041 |
|
| 6042 |
def testTimeoutZero(self): |
| 6043 |
ok = False |
| 6044 |
try: |
| 6045 |
self.serv.settimeout(0.0) |
| 6046 |
foo = self.serv.accept() |
| 6047 |
except TimeoutError: |
| 6048 |
self.fail("caught timeout instead of error (TCP)") |
| 6049 |
except OSError: |
| 6050 |
ok = True |
| 6051 |
except: |
| 6052 |
self.fail("caught unexpected exception (TCP)") |
| 6053 |
if not ok: |
| 6054 |
self.fail("accept() returned success when we did not expect it") |
| 6055 |
|
| 6056 |
@unittest.skipUnless(hasattr(signal, 'alarm'), |
| 6057 |
'test needs signal.alarm()') |
| 6058 |
def testInterruptedTimeout(self): |
| 6059 |
# XXX I don't know how to do this test on MSWindows or any other |
| 6060 |
# platform that doesn't support signal.alarm() or os.kill(), though |
| 6061 |
# the bug should have existed on all platforms. |
| 6062 |
self.serv.settimeout(5.0) # must be longer than alarm |
| 6063 |
class Alarm(Exception): |
| 6064 |
pass |
| 6065 |
def alarm_handler(signal, frame): |
| 6066 |
raise Alarm |
| 6067 |
old_alarm = signal.signal(signal.SIGALRM, alarm_handler) |
| 6068 |
try: |
| 6069 |
try: |
| 6070 |
signal.alarm(2) # POSIX allows alarm to be up to 1 second early |
| 6071 |
foo = self.serv.accept() |
| 6072 |
except TimeoutError: |
| 6073 |
self.fail("caught timeout instead of Alarm") |
| 6074 |
except Alarm: |
| 6075 |
pass |
| 6076 |
except BaseException as e: |
| 6077 |
self.fail("caught other exception instead of Alarm:" |
| 6078 |
" %s(%s):\n%s" % |
| 6079 |
(type(e), e, traceback.format_exc())) |
| 6080 |
else: |
| 6081 |
self.fail("nothing caught") |
| 6082 |
finally: |
| 6083 |
signal.alarm(0) # shut off alarm |
| 6084 |
except Alarm: |
| 6085 |
self.fail("got Alarm in wrong place") |
| 6086 |
finally: |
| 6087 |
# no alarm can be pending. Safe to restore old handler. |
| 6088 |
signal.signal(signal.SIGALRM, old_alarm) |
| 6089 |
|
| 6090 |
class UDPTimeoutTest(SocketUDPTest): |
| 6091 |
|
| 6092 |
def testUDPTimeout(self): |
| 6093 |
def raise_timeout(*args, **kwargs): |
| 6094 |
self.serv.settimeout(1.0) |
| 6095 |
self.serv.recv(1024) |
| 6096 |
self.assertRaises(TimeoutError, raise_timeout, |
| 6097 |
"Error generating a timeout exception (UDP)") |
| 6098 |
|
| 6099 |
def testTimeoutZero(self): |
| 6100 |
ok = False |
| 6101 |
try: |
| 6102 |
self.serv.settimeout(0.0) |
| 6103 |
foo = self.serv.recv(1024) |
| 6104 |
except TimeoutError: |
| 6105 |
self.fail("caught timeout instead of error (UDP)") |
| 6106 |
except OSError: |
| 6107 |
ok = True |
| 6108 |
except: |
| 6109 |
self.fail("caught unexpected exception (UDP)") |
| 6110 |
if not ok: |
| 6111 |
self.fail("recv() returned success when we did not expect it") |
| 6112 |
|
| 6113 |
@unittest.skipUnless(HAVE_SOCKET_UDPLITE, |
| 6114 |
'UDPLITE sockets required for this test.') |
| 6115 |
class UDPLITETimeoutTest(SocketUDPLITETest): |
| 6116 |
|
| 6117 |
def testUDPLITETimeout(self): |
| 6118 |
def raise_timeout(*args, **kwargs): |
| 6119 |
self.serv.settimeout(1.0) |
| 6120 |
self.serv.recv(1024) |
| 6121 |
self.assertRaises(TimeoutError, raise_timeout, |
| 6122 |
"Error generating a timeout exception (UDPLITE)") |
| 6123 |
|
| 6124 |
def testTimeoutZero(self): |
| 6125 |
ok = False |
| 6126 |
try: |
| 6127 |
self.serv.settimeout(0.0) |
| 6128 |
foo = self.serv.recv(1024) |
| 6129 |
except TimeoutError: |
| 6130 |
self.fail("caught timeout instead of error (UDPLITE)") |
| 6131 |
except OSError: |
| 6132 |
ok = True |
| 6133 |
except: |
| 6134 |
self.fail("caught unexpected exception (UDPLITE)") |
| 6135 |
if not ok: |
| 6136 |
self.fail("recv() returned success when we did not expect it") |
| 6137 |
|
| 6138 |
class TestExceptions(unittest.TestCase): |
| 6139 |
|
| 6140 |
def testExceptionTree(self): |
| 6141 |
self.assertIsSubclass(OSError, Exception) |
| 6142 |
self.assertIsSubclass(socket.herror, OSError) |
| 6143 |
self.assertIsSubclass(socket.gaierror, OSError) |
| 6144 |
self.assertIsSubclass(socket.timeout, OSError) |
| 6145 |
self.assertIs(socket.error, OSError) |
| 6146 |
self.assertIs(socket.timeout, TimeoutError) |
| 6147 |
|
| 6148 |
def test_setblocking_invalidfd(self): |
| 6149 |
# Regression test for issue #28471 |
| 6150 |
|
| 6151 |
sock0 = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) |
| 6152 |
sock = socket.socket( |
| 6153 |
socket.AF_INET, socket.SOCK_STREAM, 0, sock0.fileno()) |
| 6154 |
sock0.close() |
| 6155 |
self.addCleanup(sock.detach) |
| 6156 |
|
| 6157 |
with self.assertRaises(OSError): |
| 6158 |
sock.setblocking(False) |
| 6159 |
|
| 6160 |
|
| 6161 |
@unittest.skipUnless(sys.platform in ('linux', 'android'), 'Linux specific test') |
| 6162 |
class TestLinuxAbstractNamespace(unittest.TestCase): |
| 6163 |
|
| 6164 |
UNIX_PATH_MAX = 108 |
| 6165 |
|
| 6166 |
def testLinuxAbstractNamespace(self): |
| 6167 |
address = b"\x00python-test-hello\x00\xff" |
| 6168 |
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s1: |
| 6169 |
s1.bind(address) |
| 6170 |
s1.listen() |
| 6171 |
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s2: |
| 6172 |
s2.connect(s1.getsockname()) |
| 6173 |
with s1.accept()[0] as s3: |
| 6174 |
self.assertEqual(s1.getsockname(), address) |
| 6175 |
self.assertEqual(s2.getpeername(), address) |
| 6176 |
|
| 6177 |
def testMaxName(self): |
| 6178 |
address = b"\x00" + b"h" * (self.UNIX_PATH_MAX - 1) |
| 6179 |
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s: |
| 6180 |
s.bind(address) |
| 6181 |
self.assertEqual(s.getsockname(), address) |
| 6182 |
|
| 6183 |
def testNameOverflow(self): |
| 6184 |
address = "\x00" + "h" * self.UNIX_PATH_MAX |
| 6185 |
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s: |
| 6186 |
self.assertRaises(OSError, s.bind, address) |
| 6187 |
|
| 6188 |
def testStrName(self): |
| 6189 |
# Check that an abstract name can be passed as a string. |
| 6190 |
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
| 6191 |
try: |
| 6192 |
s.bind("\x00python\x00test\x00") |
| 6193 |
self.assertEqual(s.getsockname(), b"\x00python\x00test\x00") |
| 6194 |
finally: |
| 6195 |
s.close() |
| 6196 |
|
| 6197 |
def testBytearrayName(self): |
| 6198 |
# Check that an abstract name can be passed as a bytearray. |
| 6199 |
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s: |
| 6200 |
s.bind(bytearray(b"\x00python\x00test\x00")) |
| 6201 |
self.assertEqual(s.getsockname(), b"\x00python\x00test\x00") |
| 6202 |
|
| 6203 |
def testAutobind(self): |
| 6204 |
# Check that binding to an empty string binds to an available address |
| 6205 |
# in the abstract namespace as specified in unix(7) "Autobind feature". |
| 6206 |
abstract_address = b"^\0[0-9a-f]{5}" |
| 6207 |
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s1: |
| 6208 |
s1.bind("") |
| 6209 |
self.assertRegex(s1.getsockname(), abstract_address) |
| 6210 |
# Each socket is bound to a different abstract address. |
| 6211 |
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s2: |
| 6212 |
s2.bind("") |
| 6213 |
self.assertRegex(s2.getsockname(), abstract_address) |
| 6214 |
self.assertNotEqual(s1.getsockname(), s2.getsockname()) |
| 6215 |
|
| 6216 |
|
| 6217 |
@unittest.skipUnless(hasattr(socket, 'AF_UNIX'), 'test needs socket.AF_UNIX') |
| 6218 |
class TestUnixDomain(unittest.TestCase): |
| 6219 |
|
| 6220 |
def setUp(self): |
| 6221 |
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
| 6222 |
|
| 6223 |
def tearDown(self): |
| 6224 |
self.sock.close() |
| 6225 |
|
| 6226 |
def encoded(self, path): |
| 6227 |
# Return the given path encoded in the file system encoding, |
| 6228 |
# or skip the test if this is not possible. |
| 6229 |
try: |
| 6230 |
return os.fsencode(path) |
| 6231 |
except UnicodeEncodeError: |
| 6232 |
self.skipTest( |
| 6233 |
"Pathname {0!a} cannot be represented in file " |
| 6234 |
"system encoding {1!r}".format( |
| 6235 |
path, sys.getfilesystemencoding())) |
| 6236 |
|
| 6237 |
def bind(self, sock, path): |
| 6238 |
# Bind the socket |
| 6239 |
try: |
| 6240 |
socket_helper.bind_unix_socket(sock, path) |
| 6241 |
except OSError as e: |
| 6242 |
if str(e) == "AF_UNIX path too long": |
| 6243 |
self.skipTest( |
| 6244 |
"Pathname {0!a} is too long to serve as an AF_UNIX path" |
| 6245 |
.format(path)) |
| 6246 |
else: |
| 6247 |
raise |
| 6248 |
|
| 6249 |
def testUnbound(self): |
| 6250 |
# Issue #30205 (note getsockname() can return None on OS X) |
| 6251 |
self.assertIn(self.sock.getsockname(), ('', None)) |
| 6252 |
|
| 6253 |
def testStrAddr(self): |
| 6254 |
# Test binding to and retrieving a normal string pathname. |
| 6255 |
path = os.path.abspath(os_helper.TESTFN) |
| 6256 |
self.bind(self.sock, path) |
| 6257 |
self.addCleanup(os_helper.unlink, path) |
| 6258 |
self.assertEqual(self.sock.getsockname(), path) |
| 6259 |
|
| 6260 |
def testBytesAddr(self): |
| 6261 |
# Test binding to a bytes pathname. |
| 6262 |
path = os.path.abspath(os_helper.TESTFN) |
| 6263 |
self.bind(self.sock, self.encoded(path)) |
| 6264 |
self.addCleanup(os_helper.unlink, path) |
| 6265 |
self.assertEqual(self.sock.getsockname(), path) |
| 6266 |
|
| 6267 |
def testSurrogateescapeBind(self): |
| 6268 |
# Test binding to a valid non-ASCII pathname, with the |
| 6269 |
# non-ASCII bytes supplied using surrogateescape encoding. |
| 6270 |
path = os.path.abspath(os_helper.TESTFN_UNICODE) |
| 6271 |
b = self.encoded(path) |
| 6272 |
self.bind(self.sock, b.decode("ascii", "surrogateescape")) |
| 6273 |
self.addCleanup(os_helper.unlink, path) |
| 6274 |
self.assertEqual(self.sock.getsockname(), path) |
| 6275 |
|
| 6276 |
def testUnencodableAddr(self): |
| 6277 |
# Test binding to a pathname that cannot be encoded in the |
| 6278 |
# file system encoding. |
| 6279 |
if os_helper.TESTFN_UNENCODABLE is None: |
| 6280 |
self.skipTest("No unencodable filename available") |
| 6281 |
path = os.path.abspath(os_helper.TESTFN_UNENCODABLE) |
| 6282 |
self.bind(self.sock, path) |
| 6283 |
self.addCleanup(os_helper.unlink, path) |
| 6284 |
self.assertEqual(self.sock.getsockname(), path) |
| 6285 |
|
| 6286 |
@unittest.skipIf(sys.platform in ('linux', 'android'), |
| 6287 |
'Linux behavior is tested by TestLinuxAbstractNamespace') |
| 6288 |
def testEmptyAddress(self): |
| 6289 |
# Test that binding empty address fails. |
| 6290 |
self.assertRaises(OSError, self.sock.bind, "") |
| 6291 |
|
| 6292 |
|
| 6293 |
class BufferIOTest(SocketConnectedTest): |
| 6294 |
""" |
| 6295 |
Test the buffer versions of socket.recv() and socket.send(). |
| 6296 |
""" |
| 6297 |
def __init__(self, methodName='runTest'): |
| 6298 |
SocketConnectedTest.__init__(self, methodName=methodName) |
| 6299 |
|
| 6300 |
def testRecvIntoArray(self): |
| 6301 |
buf = array.array("B", [0] * len(MSG)) |
| 6302 |
nbytes = self.cli_conn.recv_into(buf) |
| 6303 |
self.assertEqual(nbytes, len(MSG)) |
| 6304 |
buf = buf.tobytes() |
| 6305 |
msg = buf[:len(MSG)] |
| 6306 |
self.assertEqual(msg, MSG) |
| 6307 |
|
| 6308 |
def _testRecvIntoArray(self): |
| 6309 |
buf = bytes(MSG) |
| 6310 |
self.serv_conn.send(buf) |
| 6311 |
|
| 6312 |
def testRecvIntoBytearray(self): |
| 6313 |
buf = bytearray(1024) |
| 6314 |
nbytes = self.cli_conn.recv_into(buf) |
| 6315 |
self.assertEqual(nbytes, len(MSG)) |
| 6316 |
msg = buf[:len(MSG)] |
| 6317 |
self.assertEqual(msg, MSG) |
| 6318 |
|
| 6319 |
_testRecvIntoBytearray = _testRecvIntoArray |
| 6320 |
|
| 6321 |
def testRecvIntoMemoryview(self): |
| 6322 |
buf = bytearray(1024) |
| 6323 |
nbytes = self.cli_conn.recv_into(memoryview(buf)) |
| 6324 |
self.assertEqual(nbytes, len(MSG)) |
| 6325 |
msg = buf[:len(MSG)] |
| 6326 |
self.assertEqual(msg, MSG) |
| 6327 |
|
| 6328 |
_testRecvIntoMemoryview = _testRecvIntoArray |
| 6329 |
|
| 6330 |
def testRecvFromIntoArray(self): |
| 6331 |
buf = array.array("B", [0] * len(MSG)) |
| 6332 |
nbytes, addr = self.cli_conn.recvfrom_into(buf) |
| 6333 |
self.assertEqual(nbytes, len(MSG)) |
| 6334 |
buf = buf.tobytes() |
| 6335 |
msg = buf[:len(MSG)] |
| 6336 |
self.assertEqual(msg, MSG) |
| 6337 |
|
| 6338 |
def _testRecvFromIntoArray(self): |
| 6339 |
buf = bytes(MSG) |
| 6340 |
self.serv_conn.send(buf) |
| 6341 |
|
| 6342 |
def testRecvFromIntoBytearray(self): |
| 6343 |
buf = bytearray(1024) |
| 6344 |
nbytes, addr = self.cli_conn.recvfrom_into(buf) |
| 6345 |
self.assertEqual(nbytes, len(MSG)) |
| 6346 |
msg = buf[:len(MSG)] |
| 6347 |
self.assertEqual(msg, MSG) |
| 6348 |
|
| 6349 |
_testRecvFromIntoBytearray = _testRecvFromIntoArray |
| 6350 |
|
| 6351 |
def testRecvFromIntoMemoryview(self): |
| 6352 |
buf = bytearray(1024) |
| 6353 |
nbytes, addr = self.cli_conn.recvfrom_into(memoryview(buf)) |
| 6354 |
self.assertEqual(nbytes, len(MSG)) |
| 6355 |
msg = buf[:len(MSG)] |
| 6356 |
self.assertEqual(msg, MSG) |
| 6357 |
|
| 6358 |
_testRecvFromIntoMemoryview = _testRecvFromIntoArray |
| 6359 |
|
| 6360 |
def testRecvFromIntoSmallBuffer(self): |
| 6361 |
# See issue #20246. |
| 6362 |
buf = bytearray(8) |
| 6363 |
self.assertRaises(ValueError, self.cli_conn.recvfrom_into, buf, 1024) |
| 6364 |
|
| 6365 |
def _testRecvFromIntoSmallBuffer(self): |
| 6366 |
self.serv_conn.send(MSG) |
| 6367 |
|
| 6368 |
def testRecvFromIntoEmptyBuffer(self): |
| 6369 |
buf = bytearray() |
| 6370 |
self.cli_conn.recvfrom_into(buf) |
| 6371 |
self.cli_conn.recvfrom_into(buf, 0) |
| 6372 |
|
| 6373 |
_testRecvFromIntoEmptyBuffer = _testRecvFromIntoArray |
| 6374 |
|
| 6375 |
|
| 6376 |
TIPC_STYPE = 2000 |
| 6377 |
TIPC_LOWER = 200 |
| 6378 |
TIPC_UPPER = 210 |
| 6379 |
|
| 6380 |
def isTipcAvailable(): |
| 6381 |
"""Check if the TIPC module is loaded |
| 6382 |
|
| 6383 |
The TIPC module is not loaded automatically on Ubuntu and probably |
| 6384 |
other Linux distros. |
| 6385 |
""" |
| 6386 |
if not hasattr(socket, "AF_TIPC"): |
| 6387 |
return False |
| 6388 |
try: |
| 6389 |
f = open("/proc/modules", encoding="utf-8") |
| 6390 |
except (FileNotFoundError, IsADirectoryError, PermissionError): |
| 6391 |
# It's ok if the file does not exist, is a directory or if we |
| 6392 |
# have not the permission to read it. |
| 6393 |
return False |
| 6394 |
with f: |
| 6395 |
for line in f: |
| 6396 |
if line.startswith("tipc "): |
| 6397 |
return True |
| 6398 |
return False |
| 6399 |
|
| 6400 |
@unittest.skipUnless(isTipcAvailable(), |
| 6401 |
"TIPC module is not loaded, please 'sudo modprobe tipc'") |
| 6402 |
class TIPCTest(unittest.TestCase): |
| 6403 |
def testRDM(self): |
| 6404 |
srv = socket.socket(socket.AF_TIPC, socket.SOCK_RDM) |
| 6405 |
cli = socket.socket(socket.AF_TIPC, socket.SOCK_RDM) |
| 6406 |
self.addCleanup(srv.close) |
| 6407 |
self.addCleanup(cli.close) |
| 6408 |
|
| 6409 |
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 6410 |
srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE, |
| 6411 |
TIPC_LOWER, TIPC_UPPER) |
| 6412 |
srv.bind(srvaddr) |
| 6413 |
|
| 6414 |
sendaddr = (socket.TIPC_ADDR_NAME, TIPC_STYPE, |
| 6415 |
TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0) |
| 6416 |
cli.sendto(MSG, sendaddr) |
| 6417 |
|
| 6418 |
msg, recvaddr = srv.recvfrom(1024) |
| 6419 |
|
| 6420 |
self.assertEqual(cli.getsockname(), recvaddr) |
| 6421 |
self.assertEqual(msg, MSG) |
| 6422 |
|
| 6423 |
|
| 6424 |
@unittest.skipUnless(isTipcAvailable(), |
| 6425 |
"TIPC module is not loaded, please 'sudo modprobe tipc'") |
| 6426 |
class TIPCThreadableTest(unittest.TestCase, ThreadableTest): |
| 6427 |
def __init__(self, methodName = 'runTest'): |
| 6428 |
unittest.TestCase.__init__(self, methodName = methodName) |
| 6429 |
ThreadableTest.__init__(self) |
| 6430 |
|
| 6431 |
def setUp(self): |
| 6432 |
self.srv = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM) |
| 6433 |
self.addCleanup(self.srv.close) |
| 6434 |
self.srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 6435 |
srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE, |
| 6436 |
TIPC_LOWER, TIPC_UPPER) |
| 6437 |
self.srv.bind(srvaddr) |
| 6438 |
self.srv.listen() |
| 6439 |
self.serverExplicitReady() |
| 6440 |
self.conn, self.connaddr = self.srv.accept() |
| 6441 |
self.addCleanup(self.conn.close) |
| 6442 |
|
| 6443 |
def clientSetUp(self): |
| 6444 |
# There is a hittable race between serverExplicitReady() and the |
| 6445 |
# accept() call; sleep a little while to avoid it, otherwise |
| 6446 |
# we could get an exception |
| 6447 |
time.sleep(0.1) |
| 6448 |
self.cli = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM) |
| 6449 |
self.addCleanup(self.cli.close) |
| 6450 |
addr = (socket.TIPC_ADDR_NAME, TIPC_STYPE, |
| 6451 |
TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0) |
| 6452 |
self.cli.connect(addr) |
| 6453 |
self.cliaddr = self.cli.getsockname() |
| 6454 |
|
| 6455 |
def testStream(self): |
| 6456 |
msg = self.conn.recv(1024) |
| 6457 |
self.assertEqual(msg, MSG) |
| 6458 |
self.assertEqual(self.cliaddr, self.connaddr) |
| 6459 |
|
| 6460 |
def _testStream(self): |
| 6461 |
self.cli.send(MSG) |
| 6462 |
self.cli.close() |
| 6463 |
|
| 6464 |
|
| 6465 |
class ContextManagersTest(ThreadedTCPSocketTest): |
| 6466 |
|
| 6467 |
def _testSocketClass(self): |
| 6468 |
# base test |
| 6469 |
with socket.socket() as sock: |
| 6470 |
self.assertFalse(sock._closed) |
| 6471 |
self.assertTrue(sock._closed) |
| 6472 |
# close inside with block |
| 6473 |
with socket.socket() as sock: |
| 6474 |
sock.close() |
| 6475 |
self.assertTrue(sock._closed) |
| 6476 |
# exception inside with block |
| 6477 |
with socket.socket() as sock: |
| 6478 |
self.assertRaises(OSError, sock.sendall, b'foo') |
| 6479 |
self.assertTrue(sock._closed) |
| 6480 |
|
| 6481 |
def testCreateConnectionBase(self): |
| 6482 |
conn, addr = self.serv.accept() |
| 6483 |
self.addCleanup(conn.close) |
| 6484 |
data = conn.recv(1024) |
| 6485 |
conn.sendall(data) |
| 6486 |
|
| 6487 |
def _testCreateConnectionBase(self): |
| 6488 |
address = self.serv.getsockname() |
| 6489 |
with socket.create_connection(address) as sock: |
| 6490 |
self.assertFalse(sock._closed) |
| 6491 |
sock.sendall(b'foo') |
| 6492 |
self.assertEqual(sock.recv(1024), b'foo') |
| 6493 |
self.assertTrue(sock._closed) |
| 6494 |
|
| 6495 |
def testCreateConnectionClose(self): |
| 6496 |
conn, addr = self.serv.accept() |
| 6497 |
self.addCleanup(conn.close) |
| 6498 |
data = conn.recv(1024) |
| 6499 |
conn.sendall(data) |
| 6500 |
|
| 6501 |
def _testCreateConnectionClose(self): |
| 6502 |
address = self.serv.getsockname() |
| 6503 |
with socket.create_connection(address) as sock: |
| 6504 |
sock.close() |
| 6505 |
self.assertTrue(sock._closed) |
| 6506 |
self.assertRaises(OSError, sock.sendall, b'foo') |
| 6507 |
|
| 6508 |
|
| 6509 |
class InheritanceTest(unittest.TestCase): |
| 6510 |
@unittest.skipUnless(hasattr(socket, "SOCK_CLOEXEC"), |
| 6511 |
"SOCK_CLOEXEC not defined") |
| 6512 |
@support.requires_linux_version(2, 6, 28) |
| 6513 |
def test_SOCK_CLOEXEC(self): |
| 6514 |
with socket.socket(socket.AF_INET, |
| 6515 |
socket.SOCK_STREAM | socket.SOCK_CLOEXEC) as s: |
| 6516 |
self.assertEqual(s.type, socket.SOCK_STREAM) |
| 6517 |
self.assertFalse(s.get_inheritable()) |
| 6518 |
|
| 6519 |
def test_default_inheritable(self): |
| 6520 |
sock = socket.socket() |
| 6521 |
with sock: |
| 6522 |
self.assertEqual(sock.get_inheritable(), False) |
| 6523 |
|
| 6524 |
def test_dup(self): |
| 6525 |
sock = socket.socket() |
| 6526 |
with sock: |
| 6527 |
newsock = sock.dup() |
| 6528 |
sock.close() |
| 6529 |
with newsock: |
| 6530 |
self.assertEqual(newsock.get_inheritable(), False) |
| 6531 |
|
| 6532 |
def test_set_inheritable(self): |
| 6533 |
sock = socket.socket() |
| 6534 |
with sock: |
| 6535 |
sock.set_inheritable(True) |
| 6536 |
self.assertEqual(sock.get_inheritable(), True) |
| 6537 |
|
| 6538 |
sock.set_inheritable(False) |
| 6539 |
self.assertEqual(sock.get_inheritable(), False) |
| 6540 |
|
| 6541 |
@unittest.skipIf(fcntl is None, "need fcntl") |
| 6542 |
def test_get_inheritable_cloexec(self): |
| 6543 |
sock = socket.socket() |
| 6544 |
with sock: |
| 6545 |
fd = sock.fileno() |
| 6546 |
self.assertEqual(sock.get_inheritable(), False) |
| 6547 |
|
| 6548 |
# clear FD_CLOEXEC flag |
| 6549 |
flags = fcntl.fcntl(fd, fcntl.F_GETFD) |
| 6550 |
flags &= ~fcntl.FD_CLOEXEC |
| 6551 |
fcntl.fcntl(fd, fcntl.F_SETFD, flags) |
| 6552 |
|
| 6553 |
self.assertEqual(sock.get_inheritable(), True) |
| 6554 |
|
| 6555 |
@unittest.skipIf(fcntl is None, "need fcntl") |
| 6556 |
def test_set_inheritable_cloexec(self): |
| 6557 |
sock = socket.socket() |
| 6558 |
with sock: |
| 6559 |
fd = sock.fileno() |
| 6560 |
self.assertEqual(fcntl.fcntl(fd, fcntl.F_GETFD) & fcntl.FD_CLOEXEC, |
| 6561 |
fcntl.FD_CLOEXEC) |
| 6562 |
|
| 6563 |
sock.set_inheritable(True) |
| 6564 |
self.assertEqual(fcntl.fcntl(fd, fcntl.F_GETFD) & fcntl.FD_CLOEXEC, |
| 6565 |
0) |
| 6566 |
|
| 6567 |
|
| 6568 |
def test_socketpair(self): |
| 6569 |
s1, s2 = socket.socketpair() |
| 6570 |
self.addCleanup(s1.close) |
| 6571 |
self.addCleanup(s2.close) |
| 6572 |
self.assertEqual(s1.get_inheritable(), False) |
| 6573 |
self.assertEqual(s2.get_inheritable(), False) |
| 6574 |
|
| 6575 |
|
| 6576 |
@unittest.skipUnless(hasattr(socket, "SOCK_NONBLOCK"), |
| 6577 |
"SOCK_NONBLOCK not defined") |
| 6578 |
class NonblockConstantTest(unittest.TestCase): |
| 6579 |
def checkNonblock(self, s, nonblock=True, timeout=0.0): |
| 6580 |
if nonblock: |
| 6581 |
self.assertEqual(s.type, socket.SOCK_STREAM) |
| 6582 |
self.assertEqual(s.gettimeout(), timeout) |
| 6583 |
self.assertTrue( |
| 6584 |
fcntl.fcntl(s, fcntl.F_GETFL, os.O_NONBLOCK) & os.O_NONBLOCK) |
| 6585 |
if timeout == 0: |
| 6586 |
# timeout == 0: means that getblocking() must be False. |
| 6587 |
self.assertFalse(s.getblocking()) |
| 6588 |
else: |
| 6589 |
# If timeout > 0, the socket will be in a "blocking" mode |
| 6590 |
# from the standpoint of the Python API. For Python socket |
| 6591 |
# object, "blocking" means that operations like 'sock.recv()' |
| 6592 |
# will block. Internally, file descriptors for |
| 6593 |
# "blocking" Python sockets *with timeouts* are in a |
| 6594 |
# *non-blocking* mode, and 'sock.recv()' uses 'select()' |
| 6595 |
# and handles EWOULDBLOCK/EAGAIN to enforce the timeout. |
| 6596 |
self.assertTrue(s.getblocking()) |
| 6597 |
else: |
| 6598 |
self.assertEqual(s.type, socket.SOCK_STREAM) |
| 6599 |
self.assertEqual(s.gettimeout(), None) |
| 6600 |
self.assertFalse( |
| 6601 |
fcntl.fcntl(s, fcntl.F_GETFL, os.O_NONBLOCK) & os.O_NONBLOCK) |
| 6602 |
self.assertTrue(s.getblocking()) |
| 6603 |
|
| 6604 |
@support.requires_linux_version(2, 6, 28) |
| 6605 |
def test_SOCK_NONBLOCK(self): |
| 6606 |
# a lot of it seems silly and redundant, but I wanted to test that |
| 6607 |
# changing back and forth worked ok |
| 6608 |
with socket.socket(socket.AF_INET, |
| 6609 |
socket.SOCK_STREAM | socket.SOCK_NONBLOCK) as s: |
| 6610 |
self.checkNonblock(s) |
| 6611 |
s.setblocking(True) |
| 6612 |
self.checkNonblock(s, nonblock=False) |
| 6613 |
s.setblocking(False) |
| 6614 |
self.checkNonblock(s) |
| 6615 |
s.settimeout(None) |
| 6616 |
self.checkNonblock(s, nonblock=False) |
| 6617 |
s.settimeout(2.0) |
| 6618 |
self.checkNonblock(s, timeout=2.0) |
| 6619 |
s.setblocking(True) |
| 6620 |
self.checkNonblock(s, nonblock=False) |
| 6621 |
# defaulttimeout |
| 6622 |
t = socket.getdefaulttimeout() |
| 6623 |
socket.setdefaulttimeout(0.0) |
| 6624 |
with socket.socket() as s: |
| 6625 |
self.checkNonblock(s) |
| 6626 |
socket.setdefaulttimeout(None) |
| 6627 |
with socket.socket() as s: |
| 6628 |
self.checkNonblock(s, False) |
| 6629 |
socket.setdefaulttimeout(2.0) |
| 6630 |
with socket.socket() as s: |
| 6631 |
self.checkNonblock(s, timeout=2.0) |
| 6632 |
socket.setdefaulttimeout(None) |
| 6633 |
with socket.socket() as s: |
| 6634 |
self.checkNonblock(s, False) |
| 6635 |
socket.setdefaulttimeout(t) |
| 6636 |
|
| 6637 |
|
| 6638 |
@unittest.skipUnless(os.name == "nt", "Windows specific") |
| 6639 |
@unittest.skipUnless(multiprocessing, "need multiprocessing") |
| 6640 |
class TestSocketSharing(SocketTCPTest): |
| 6641 |
# This must be classmethod and not staticmethod or multiprocessing |
| 6642 |
# won't be able to bootstrap it. |
| 6643 |
@classmethod |
| 6644 |
def remoteProcessServer(cls, q): |
| 6645 |
# Recreate socket from shared data |
| 6646 |
sdata = q.get() |
| 6647 |
message = q.get() |
| 6648 |
|
| 6649 |
s = socket.fromshare(sdata) |
| 6650 |
s2, c = s.accept() |
| 6651 |
|
| 6652 |
# Send the message |
| 6653 |
s2.sendall(message) |
| 6654 |
s2.close() |
| 6655 |
s.close() |
| 6656 |
|
| 6657 |
def testShare(self): |
| 6658 |
# Transfer the listening server socket to another process |
| 6659 |
# and service it from there. |
| 6660 |
|
| 6661 |
# Create process: |
| 6662 |
q = multiprocessing.Queue() |
| 6663 |
p = multiprocessing.Process(target=self.remoteProcessServer, args=(q,)) |
| 6664 |
p.start() |
| 6665 |
|
| 6666 |
# Get the shared socket data |
| 6667 |
data = self.serv.share(p.pid) |
| 6668 |
|
| 6669 |
# Pass the shared socket to the other process |
| 6670 |
addr = self.serv.getsockname() |
| 6671 |
self.serv.close() |
| 6672 |
q.put(data) |
| 6673 |
|
| 6674 |
# The data that the server will send us |
| 6675 |
message = b"slapmahfro" |
| 6676 |
q.put(message) |
| 6677 |
|
| 6678 |
# Connect |
| 6679 |
s = socket.create_connection(addr) |
| 6680 |
# listen for the data |
| 6681 |
m = [] |
| 6682 |
while True: |
| 6683 |
data = s.recv(100) |
| 6684 |
if not data: |
| 6685 |
break |
| 6686 |
m.append(data) |
| 6687 |
s.close() |
| 6688 |
received = b"".join(m) |
| 6689 |
self.assertEqual(received, message) |
| 6690 |
p.join() |
| 6691 |
|
| 6692 |
def testShareLength(self): |
| 6693 |
data = self.serv.share(os.getpid()) |
| 6694 |
self.assertRaises(ValueError, socket.fromshare, data[:-1]) |
| 6695 |
self.assertRaises(ValueError, socket.fromshare, data+b"foo") |
| 6696 |
|
| 6697 |
def compareSockets(self, org, other): |
| 6698 |
# socket sharing is expected to work only for blocking socket |
| 6699 |
# since the internal python timeout value isn't transferred. |
| 6700 |
self.assertEqual(org.gettimeout(), None) |
| 6701 |
self.assertEqual(org.gettimeout(), other.gettimeout()) |
| 6702 |
|
| 6703 |
self.assertEqual(org.family, other.family) |
| 6704 |
self.assertEqual(org.type, other.type) |
| 6705 |
# If the user specified "0" for proto, then |
| 6706 |
# internally windows will have picked the correct value. |
| 6707 |
# Python introspection on the socket however will still return |
| 6708 |
# 0. For the shared socket, the python value is recreated |
| 6709 |
# from the actual value, so it may not compare correctly. |
| 6710 |
if org.proto != 0: |
| 6711 |
self.assertEqual(org.proto, other.proto) |
| 6712 |
|
| 6713 |
def testShareLocal(self): |
| 6714 |
data = self.serv.share(os.getpid()) |
| 6715 |
s = socket.fromshare(data) |
| 6716 |
try: |
| 6717 |
self.compareSockets(self.serv, s) |
| 6718 |
finally: |
| 6719 |
s.close() |
| 6720 |
|
| 6721 |
def testTypes(self): |
| 6722 |
families = [socket.AF_INET, socket.AF_INET6] |
| 6723 |
types = [socket.SOCK_STREAM, socket.SOCK_DGRAM] |
| 6724 |
for f in families: |
| 6725 |
for t in types: |
| 6726 |
try: |
| 6727 |
source = socket.socket(f, t) |
| 6728 |
except OSError: |
| 6729 |
continue # This combination is not supported |
| 6730 |
try: |
| 6731 |
data = source.share(os.getpid()) |
| 6732 |
shared = socket.fromshare(data) |
| 6733 |
try: |
| 6734 |
self.compareSockets(source, shared) |
| 6735 |
finally: |
| 6736 |
shared.close() |
| 6737 |
finally: |
| 6738 |
source.close() |
| 6739 |
|
| 6740 |
|
| 6741 |
class SendfileUsingSendTest(ThreadedTCPSocketTest): |
| 6742 |
""" |
| 6743 |
Test the send() implementation of socket.sendfile(). |
| 6744 |
""" |
| 6745 |
|
| 6746 |
FILESIZE = (10 * 1024 * 1024) # 10 MiB |
| 6747 |
BUFSIZE = 8192 |
| 6748 |
FILEDATA = b"" |
| 6749 |
TIMEOUT = support.LOOPBACK_TIMEOUT |
| 6750 |
|
| 6751 |
@classmethod |
| 6752 |
def setUpClass(cls): |
| 6753 |
def chunks(total, step): |
| 6754 |
assert total >= step |
| 6755 |
while total > step: |
| 6756 |
yield step |
| 6757 |
total -= step |
| 6758 |
if total: |
| 6759 |
yield total |
| 6760 |
|
| 6761 |
chunk = b"".join([random.choice(string.ascii_letters).encode() |
| 6762 |
for i in range(cls.BUFSIZE)]) |
| 6763 |
with open(os_helper.TESTFN, 'wb') as f: |
| 6764 |
for csize in chunks(cls.FILESIZE, cls.BUFSIZE): |
| 6765 |
f.write(chunk) |
| 6766 |
with open(os_helper.TESTFN, 'rb') as f: |
| 6767 |
cls.FILEDATA = f.read() |
| 6768 |
assert len(cls.FILEDATA) == cls.FILESIZE |
| 6769 |
|
| 6770 |
@classmethod |
| 6771 |
def tearDownClass(cls): |
| 6772 |
os_helper.unlink(os_helper.TESTFN) |
| 6773 |
|
| 6774 |
def accept_conn(self): |
| 6775 |
self.serv.settimeout(support.LONG_TIMEOUT) |
| 6776 |
conn, addr = self.serv.accept() |
| 6777 |
conn.settimeout(self.TIMEOUT) |
| 6778 |
self.addCleanup(conn.close) |
| 6779 |
return conn |
| 6780 |
|
| 6781 |
def recv_data(self, conn): |
| 6782 |
received = [] |
| 6783 |
while True: |
| 6784 |
chunk = conn.recv(self.BUFSIZE) |
| 6785 |
if not chunk: |
| 6786 |
break |
| 6787 |
received.append(chunk) |
| 6788 |
return b''.join(received) |
| 6789 |
|
| 6790 |
def meth_from_sock(self, sock): |
| 6791 |
# Depending on the mixin class being run return either send() |
| 6792 |
# or sendfile() method implementation. |
| 6793 |
return getattr(sock, "_sendfile_use_send") |
| 6794 |
|
| 6795 |
# regular file |
| 6796 |
|
| 6797 |
def _testRegularFile(self): |
| 6798 |
address = self.serv.getsockname() |
| 6799 |
file = open(os_helper.TESTFN, 'rb') |
| 6800 |
with socket.create_connection(address) as sock, file as file: |
| 6801 |
meth = self.meth_from_sock(sock) |
| 6802 |
sent = meth(file) |
| 6803 |
self.assertEqual(sent, self.FILESIZE) |
| 6804 |
self.assertEqual(file.tell(), self.FILESIZE) |
| 6805 |
|
| 6806 |
def testRegularFile(self): |
| 6807 |
conn = self.accept_conn() |
| 6808 |
data = self.recv_data(conn) |
| 6809 |
self.assertEqual(len(data), self.FILESIZE) |
| 6810 |
self.assertEqual(data, self.FILEDATA) |
| 6811 |
|
| 6812 |
# non regular file |
| 6813 |
|
| 6814 |
def _testNonRegularFile(self): |
| 6815 |
address = self.serv.getsockname() |
| 6816 |
file = io.BytesIO(self.FILEDATA) |
| 6817 |
with socket.create_connection(address) as sock, file as file: |
| 6818 |
sent = sock.sendfile(file) |
| 6819 |
self.assertEqual(sent, self.FILESIZE) |
| 6820 |
self.assertEqual(file.tell(), self.FILESIZE) |
| 6821 |
self.assertRaises(socket._GiveupOnSendfile, |
| 6822 |
sock._sendfile_use_sendfile, file) |
| 6823 |
|
| 6824 |
def testNonRegularFile(self): |
| 6825 |
conn = self.accept_conn() |
| 6826 |
data = self.recv_data(conn) |
| 6827 |
self.assertEqual(len(data), self.FILESIZE) |
| 6828 |
self.assertEqual(data, self.FILEDATA) |
| 6829 |
|
| 6830 |
# empty file |
| 6831 |
|
| 6832 |
def _testEmptyFileSend(self): |
| 6833 |
address = self.serv.getsockname() |
| 6834 |
filename = os_helper.TESTFN + "2" |
| 6835 |
with open(filename, 'wb'): |
| 6836 |
self.addCleanup(os_helper.unlink, filename) |
| 6837 |
file = open(filename, 'rb') |
| 6838 |
with socket.create_connection(address) as sock, file as file: |
| 6839 |
meth = self.meth_from_sock(sock) |
| 6840 |
sent = meth(file) |
| 6841 |
self.assertEqual(sent, 0) |
| 6842 |
self.assertEqual(file.tell(), 0) |
| 6843 |
|
| 6844 |
def testEmptyFileSend(self): |
| 6845 |
conn = self.accept_conn() |
| 6846 |
data = self.recv_data(conn) |
| 6847 |
self.assertEqual(data, b"") |
| 6848 |
|
| 6849 |
# offset |
| 6850 |
|
| 6851 |
def _testOffset(self): |
| 6852 |
address = self.serv.getsockname() |
| 6853 |
file = open(os_helper.TESTFN, 'rb') |
| 6854 |
with socket.create_connection(address) as sock, file as file: |
| 6855 |
meth = self.meth_from_sock(sock) |
| 6856 |
sent = meth(file, offset=5000) |
| 6857 |
self.assertEqual(sent, self.FILESIZE - 5000) |
| 6858 |
self.assertEqual(file.tell(), self.FILESIZE) |
| 6859 |
|
| 6860 |
def testOffset(self): |
| 6861 |
conn = self.accept_conn() |
| 6862 |
data = self.recv_data(conn) |
| 6863 |
self.assertEqual(len(data), self.FILESIZE - 5000) |
| 6864 |
self.assertEqual(data, self.FILEDATA[5000:]) |
| 6865 |
|
| 6866 |
# count |
| 6867 |
|
| 6868 |
def _testCount(self): |
| 6869 |
address = self.serv.getsockname() |
| 6870 |
file = open(os_helper.TESTFN, 'rb') |
| 6871 |
sock = socket.create_connection(address, |
| 6872 |
timeout=support.LOOPBACK_TIMEOUT) |
| 6873 |
with sock, file: |
| 6874 |
count = 5000007 |
| 6875 |
meth = self.meth_from_sock(sock) |
| 6876 |
sent = meth(file, count=count) |
| 6877 |
self.assertEqual(sent, count) |
| 6878 |
self.assertEqual(file.tell(), count) |
| 6879 |
|
| 6880 |
def testCount(self): |
| 6881 |
count = 5000007 |
| 6882 |
conn = self.accept_conn() |
| 6883 |
data = self.recv_data(conn) |
| 6884 |
self.assertEqual(len(data), count) |
| 6885 |
self.assertEqual(data, self.FILEDATA[:count]) |
| 6886 |
|
| 6887 |
# count small |
| 6888 |
|
| 6889 |
def _testCountSmall(self): |
| 6890 |
address = self.serv.getsockname() |
| 6891 |
file = open(os_helper.TESTFN, 'rb') |
| 6892 |
sock = socket.create_connection(address, |
| 6893 |
timeout=support.LOOPBACK_TIMEOUT) |
| 6894 |
with sock, file: |
| 6895 |
count = 1 |
| 6896 |
meth = self.meth_from_sock(sock) |
| 6897 |
sent = meth(file, count=count) |
| 6898 |
self.assertEqual(sent, count) |
| 6899 |
self.assertEqual(file.tell(), count) |
| 6900 |
|
| 6901 |
def testCountSmall(self): |
| 6902 |
count = 1 |
| 6903 |
conn = self.accept_conn() |
| 6904 |
data = self.recv_data(conn) |
| 6905 |
self.assertEqual(len(data), count) |
| 6906 |
self.assertEqual(data, self.FILEDATA[:count]) |
| 6907 |
|
| 6908 |
# count + offset |
| 6909 |
|
| 6910 |
def _testCountWithOffset(self): |
| 6911 |
address = self.serv.getsockname() |
| 6912 |
file = open(os_helper.TESTFN, 'rb') |
| 6913 |
with socket.create_connection(address, timeout=2) as sock, file as file: |
| 6914 |
count = 100007 |
| 6915 |
meth = self.meth_from_sock(sock) |
| 6916 |
sent = meth(file, offset=2007, count=count) |
| 6917 |
self.assertEqual(sent, count) |
| 6918 |
self.assertEqual(file.tell(), count + 2007) |
| 6919 |
|
| 6920 |
def testCountWithOffset(self): |
| 6921 |
count = 100007 |
| 6922 |
conn = self.accept_conn() |
| 6923 |
data = self.recv_data(conn) |
| 6924 |
self.assertEqual(len(data), count) |
| 6925 |
self.assertEqual(data, self.FILEDATA[2007:count+2007]) |
| 6926 |
|
| 6927 |
# non blocking sockets are not supposed to work |
| 6928 |
|
| 6929 |
def _testNonBlocking(self): |
| 6930 |
address = self.serv.getsockname() |
| 6931 |
file = open(os_helper.TESTFN, 'rb') |
| 6932 |
with socket.create_connection(address) as sock, file as file: |
| 6933 |
sock.setblocking(False) |
| 6934 |
meth = self.meth_from_sock(sock) |
| 6935 |
self.assertRaises(ValueError, meth, file) |
| 6936 |
self.assertRaises(ValueError, sock.sendfile, file) |
| 6937 |
|
| 6938 |
def testNonBlocking(self): |
| 6939 |
conn = self.accept_conn() |
| 6940 |
if conn.recv(8192): |
| 6941 |
self.fail('was not supposed to receive any data') |
| 6942 |
|
| 6943 |
# timeout (non-triggered) |
| 6944 |
|
| 6945 |
def _testWithTimeout(self): |
| 6946 |
address = self.serv.getsockname() |
| 6947 |
file = open(os_helper.TESTFN, 'rb') |
| 6948 |
sock = socket.create_connection(address, |
| 6949 |
timeout=support.LOOPBACK_TIMEOUT) |
| 6950 |
with sock, file: |
| 6951 |
meth = self.meth_from_sock(sock) |
| 6952 |
sent = meth(file) |
| 6953 |
self.assertEqual(sent, self.FILESIZE) |
| 6954 |
|
| 6955 |
def testWithTimeout(self): |
| 6956 |
conn = self.accept_conn() |
| 6957 |
data = self.recv_data(conn) |
| 6958 |
self.assertEqual(len(data), self.FILESIZE) |
| 6959 |
self.assertEqual(data, self.FILEDATA) |
| 6960 |
|
| 6961 |
# timeout (triggered) |
| 6962 |
|
| 6963 |
def _testWithTimeoutTriggeredSend(self): |
| 6964 |
address = self.serv.getsockname() |
| 6965 |
with open(os_helper.TESTFN, 'rb') as file: |
| 6966 |
with socket.create_connection(address) as sock: |
| 6967 |
sock.settimeout(0.01) |
| 6968 |
meth = self.meth_from_sock(sock) |
| 6969 |
self.assertRaises(TimeoutError, meth, file) |
| 6970 |
|
| 6971 |
def testWithTimeoutTriggeredSend(self): |
| 6972 |
conn = self.accept_conn() |
| 6973 |
conn.recv(88192) |
| 6974 |
# bpo-45212: the wait here needs to be longer than the client-side timeout (0.01s) |
| 6975 |
time.sleep(1) |
| 6976 |
|
| 6977 |
# errors |
| 6978 |
|
| 6979 |
def _test_errors(self): |
| 6980 |
pass |
| 6981 |
|
| 6982 |
def test_errors(self): |
| 6983 |
with open(os_helper.TESTFN, 'rb') as file: |
| 6984 |
with socket.socket(type=socket.SOCK_DGRAM) as s: |
| 6985 |
meth = self.meth_from_sock(s) |
| 6986 |
self.assertRaisesRegex( |
| 6987 |
ValueError, "SOCK_STREAM", meth, file) |
| 6988 |
with open(os_helper.TESTFN, encoding="utf-8") as file: |
| 6989 |
with socket.socket() as s: |
| 6990 |
meth = self.meth_from_sock(s) |
| 6991 |
self.assertRaisesRegex( |
| 6992 |
ValueError, "binary mode", meth, file) |
| 6993 |
with open(os_helper.TESTFN, 'rb') as file: |
| 6994 |
with socket.socket() as s: |
| 6995 |
meth = self.meth_from_sock(s) |
| 6996 |
self.assertRaisesRegex(TypeError, "positive integer", |
| 6997 |
meth, file, count='2') |
| 6998 |
self.assertRaisesRegex(TypeError, "positive integer", |
| 6999 |
meth, file, count=0.1) |
| 7000 |
self.assertRaisesRegex(ValueError, "positive integer", |
| 7001 |
meth, file, count=0) |
| 7002 |
self.assertRaisesRegex(ValueError, "positive integer", |
| 7003 |
meth, file, count=-1) |
| 7004 |
|
| 7005 |
|
| 7006 |
@unittest.skipUnless(hasattr(os, "sendfile"), |
| 7007 |
'os.sendfile() required for this test.') |
| 7008 |
class SendfileUsingSendfileTest(SendfileUsingSendTest): |
| 7009 |
""" |
| 7010 |
Test the sendfile() implementation of socket.sendfile(). |
| 7011 |
""" |
| 7012 |
def meth_from_sock(self, sock): |
| 7013 |
return getattr(sock, "_sendfile_use_sendfile") |
| 7014 |
|
| 7015 |
|
| 7016 |
@unittest.skipUnless(HAVE_SOCKET_ALG, 'AF_ALG required') |
| 7017 |
class LinuxKernelCryptoAPI(unittest.TestCase): |
| 7018 |
# tests for AF_ALG |
| 7019 |
def create_alg(self, typ, name): |
| 7020 |
sock = socket.socket(socket.AF_ALG, socket.SOCK_SEQPACKET, 0) |
| 7021 |
try: |
| 7022 |
sock.bind((typ, name)) |
| 7023 |
except FileNotFoundError as e: |
| 7024 |
# type / algorithm is not available |
| 7025 |
sock.close() |
| 7026 |
raise unittest.SkipTest(str(e), typ, name) |
| 7027 |
else: |
| 7028 |
return sock |
| 7029 |
|
| 7030 |
# bpo-31705: On kernel older than 4.5, sendto() failed with ENOKEY, |
| 7031 |
# at least on ppc64le architecture |
| 7032 |
@support.requires_linux_version(4, 5) |
| 7033 |
def test_sha256(self): |
| 7034 |
expected = bytes.fromhex("ba7816bf8f01cfea414140de5dae2223b00361a396" |
| 7035 |
"177a9cb410ff61f20015ad") |
| 7036 |
with self.create_alg('hash', 'sha256') as algo: |
| 7037 |
op, _ = algo.accept() |
| 7038 |
with op: |
| 7039 |
op.sendall(b"abc") |
| 7040 |
self.assertEqual(op.recv(512), expected) |
| 7041 |
|
| 7042 |
op, _ = algo.accept() |
| 7043 |
with op: |
| 7044 |
op.send(b'a', socket.MSG_MORE) |
| 7045 |
op.send(b'b', socket.MSG_MORE) |
| 7046 |
op.send(b'c', socket.MSG_MORE) |
| 7047 |
op.send(b'') |
| 7048 |
self.assertEqual(op.recv(512), expected) |
| 7049 |
|
| 7050 |
def test_hmac_sha1(self): |
| 7051 |
# gh-109396: In FIPS mode, Linux 6.5 requires a key |
| 7052 |
# of at least 112 bits. Use a key of 152 bits. |
| 7053 |
key = b"Python loves AF_ALG" |
| 7054 |
data = b"what do ya want for nothing?" |
| 7055 |
expected = bytes.fromhex("193dbb43c6297b47ea6277ec0ce67119a3f3aa66") |
| 7056 |
with self.create_alg('hash', 'hmac(sha1)') as algo: |
| 7057 |
algo.setsockopt(socket.SOL_ALG, socket.ALG_SET_KEY, key) |
| 7058 |
op, _ = algo.accept() |
| 7059 |
with op: |
| 7060 |
op.sendall(data) |
| 7061 |
self.assertEqual(op.recv(512), expected) |
| 7062 |
|
| 7063 |
# Although it should work with 3.19 and newer the test blocks on |
| 7064 |
# Ubuntu 15.10 with Kernel 4.2.0-19. |
| 7065 |
@support.requires_linux_version(4, 3) |
| 7066 |
def test_aes_cbc(self): |
| 7067 |
key = bytes.fromhex('06a9214036b8a15b512e03d534120006') |
| 7068 |
iv = bytes.fromhex('3dafba429d9eb430b422da802c9fac41') |
| 7069 |
msg = b"Single block msg" |
| 7070 |
ciphertext = bytes.fromhex('e353779c1079aeb82708942dbe77181a') |
| 7071 |
msglen = len(msg) |
| 7072 |
with self.create_alg('skcipher', 'cbc(aes)') as algo: |
| 7073 |
algo.setsockopt(socket.SOL_ALG, socket.ALG_SET_KEY, key) |
| 7074 |
op, _ = algo.accept() |
| 7075 |
with op: |
| 7076 |
op.sendmsg_afalg(op=socket.ALG_OP_ENCRYPT, iv=iv, |
| 7077 |
flags=socket.MSG_MORE) |
| 7078 |
op.sendall(msg) |
| 7079 |
self.assertEqual(op.recv(msglen), ciphertext) |
| 7080 |
|
| 7081 |
op, _ = algo.accept() |
| 7082 |
with op: |
| 7083 |
op.sendmsg_afalg([ciphertext], |
| 7084 |
op=socket.ALG_OP_DECRYPT, iv=iv) |
| 7085 |
self.assertEqual(op.recv(msglen), msg) |
| 7086 |
|
| 7087 |
# long message |
| 7088 |
multiplier = 1024 |
| 7089 |
longmsg = [msg] * multiplier |
| 7090 |
op, _ = algo.accept() |
| 7091 |
with op: |
| 7092 |
op.sendmsg_afalg(longmsg, |
| 7093 |
op=socket.ALG_OP_ENCRYPT, iv=iv) |
| 7094 |
enc = op.recv(msglen * multiplier) |
| 7095 |
self.assertEqual(len(enc), msglen * multiplier) |
| 7096 |
self.assertEqual(enc[:msglen], ciphertext) |
| 7097 |
|
| 7098 |
op, _ = algo.accept() |
| 7099 |
with op: |
| 7100 |
op.sendmsg_afalg([enc], |
| 7101 |
op=socket.ALG_OP_DECRYPT, iv=iv) |
| 7102 |
dec = op.recv(msglen * multiplier) |
| 7103 |
self.assertEqual(len(dec), msglen * multiplier) |
| 7104 |
self.assertEqual(dec, msg * multiplier) |
| 7105 |
|
| 7106 |
@support.requires_linux_version(4, 9) # see gh-73510 |
| 7107 |
def test_aead_aes_gcm(self): |
| 7108 |
kernel_version = support._get_kernel_version("Linux") |
| 7109 |
if kernel_version is not None: |
| 7110 |
if kernel_version >= (6, 16) and kernel_version < (6, 18): |
| 7111 |
# See https://github.com/python/cpython/issues/139310. |
| 7112 |
self.skipTest("upstream Linux kernel issue") |
| 7113 |
|
| 7114 |
key = bytes.fromhex('c939cc13397c1d37de6ae0e1cb7c423c') |
| 7115 |
iv = bytes.fromhex('b3d8cc017cbb89b39e0f67e2') |
| 7116 |
plain = bytes.fromhex('c3b3c41f113a31b73d9a5cd432103069') |
| 7117 |
assoc = bytes.fromhex('24825602bd12a984e0092d3e448eda5f') |
| 7118 |
expected_ct = bytes.fromhex('93fe7d9e9bfd10348a5606e5cafa7354') |
| 7119 |
expected_tag = bytes.fromhex('0032a1dc85f1c9786925a2e71d8272dd') |
| 7120 |
|
| 7121 |
taglen = len(expected_tag) |
| 7122 |
assoclen = len(assoc) |
| 7123 |
|
| 7124 |
with self.create_alg('aead', 'gcm(aes)') as algo: |
| 7125 |
algo.setsockopt(socket.SOL_ALG, socket.ALG_SET_KEY, key) |
| 7126 |
algo.setsockopt(socket.SOL_ALG, socket.ALG_SET_AEAD_AUTHSIZE, |
| 7127 |
None, taglen) |
| 7128 |
|
| 7129 |
# send assoc, plain and tag buffer in separate steps |
| 7130 |
op, _ = algo.accept() |
| 7131 |
with op: |
| 7132 |
op.sendmsg_afalg(op=socket.ALG_OP_ENCRYPT, iv=iv, |
| 7133 |
assoclen=assoclen, flags=socket.MSG_MORE) |
| 7134 |
op.sendall(assoc, socket.MSG_MORE) |
| 7135 |
op.sendall(plain) |
| 7136 |
res = op.recv(assoclen + len(plain) + taglen) |
| 7137 |
self.assertEqual(expected_ct, res[assoclen:-taglen]) |
| 7138 |
self.assertEqual(expected_tag, res[-taglen:]) |
| 7139 |
|
| 7140 |
# now with msg |
| 7141 |
op, _ = algo.accept() |
| 7142 |
with op: |
| 7143 |
msg = assoc + plain |
| 7144 |
op.sendmsg_afalg([msg], op=socket.ALG_OP_ENCRYPT, iv=iv, |
| 7145 |
assoclen=assoclen) |
| 7146 |
res = op.recv(assoclen + len(plain) + taglen) |
| 7147 |
self.assertEqual(expected_ct, res[assoclen:-taglen]) |
| 7148 |
self.assertEqual(expected_tag, res[-taglen:]) |
| 7149 |
|
| 7150 |
# create anc data manually |
| 7151 |
pack_uint32 = struct.Struct('I').pack |
| 7152 |
op, _ = algo.accept() |
| 7153 |
with op: |
| 7154 |
msg = assoc + plain |
| 7155 |
op.sendmsg( |
| 7156 |
[msg], |
| 7157 |
([socket.SOL_ALG, socket.ALG_SET_OP, pack_uint32(socket.ALG_OP_ENCRYPT)], |
| 7158 |
[socket.SOL_ALG, socket.ALG_SET_IV, pack_uint32(len(iv)) + iv], |
| 7159 |
[socket.SOL_ALG, socket.ALG_SET_AEAD_ASSOCLEN, pack_uint32(assoclen)], |
| 7160 |
) |
| 7161 |
) |
| 7162 |
res = op.recv(len(msg) + taglen) |
| 7163 |
self.assertEqual(expected_ct, res[assoclen:-taglen]) |
| 7164 |
self.assertEqual(expected_tag, res[-taglen:]) |
| 7165 |
|
| 7166 |
# decrypt and verify |
| 7167 |
op, _ = algo.accept() |
| 7168 |
with op: |
| 7169 |
msg = assoc + expected_ct + expected_tag |
| 7170 |
op.sendmsg_afalg([msg], op=socket.ALG_OP_DECRYPT, iv=iv, |
| 7171 |
assoclen=assoclen) |
| 7172 |
res = op.recv(len(msg) - taglen) |
| 7173 |
self.assertEqual(plain, res[assoclen:]) |
| 7174 |
|
| 7175 |
@support.requires_linux_version(4, 3) # see test_aes_cbc |
| 7176 |
def test_drbg_pr_sha256(self): |
| 7177 |
# deterministic random bit generator, prediction resistance, sha256 |
| 7178 |
with self.create_alg('rng', 'drbg_pr_sha256') as algo: |
| 7179 |
extra_seed = os.urandom(32) |
| 7180 |
algo.setsockopt(socket.SOL_ALG, socket.ALG_SET_KEY, extra_seed) |
| 7181 |
op, _ = algo.accept() |
| 7182 |
with op: |
| 7183 |
rn = op.recv(32) |
| 7184 |
self.assertEqual(len(rn), 32) |
| 7185 |
|
| 7186 |
def test_sendmsg_afalg_args(self): |
| 7187 |
sock = socket.socket(socket.AF_ALG, socket.SOCK_SEQPACKET, 0) |
| 7188 |
with sock: |
| 7189 |
with self.assertRaises(TypeError): |
| 7190 |
sock.sendmsg_afalg() |
| 7191 |
|
| 7192 |
with self.assertRaises(TypeError): |
| 7193 |
sock.sendmsg_afalg(op=None) |
| 7194 |
|
| 7195 |
with self.assertRaises(TypeError): |
| 7196 |
sock.sendmsg_afalg(1) |
| 7197 |
|
| 7198 |
with self.assertRaises(TypeError): |
| 7199 |
sock.sendmsg_afalg(op=socket.ALG_OP_ENCRYPT, assoclen=None) |
| 7200 |
|
| 7201 |
with self.assertRaises(TypeError): |
| 7202 |
sock.sendmsg_afalg(op=socket.ALG_OP_ENCRYPT, assoclen=-1) |
| 7203 |
|
| 7204 |
def test_length_restriction(self): |
| 7205 |
# bpo-35050, off-by-one error in length check |
| 7206 |
sock = socket.socket(socket.AF_ALG, socket.SOCK_SEQPACKET, 0) |
| 7207 |
self.addCleanup(sock.close) |
| 7208 |
|
| 7209 |
# salg_type[14] |
| 7210 |
with self.assertRaises(FileNotFoundError): |
| 7211 |
sock.bind(("t" * 13, "name")) |
| 7212 |
with self.assertRaisesRegex(ValueError, "type too long"): |
| 7213 |
sock.bind(("t" * 14, "name")) |
| 7214 |
|
| 7215 |
# salg_name[64] |
| 7216 |
with self.assertRaises(FileNotFoundError): |
| 7217 |
sock.bind(("type", "n" * 63)) |
| 7218 |
with self.assertRaisesRegex(ValueError, "name too long"): |
| 7219 |
sock.bind(("type", "n" * 64)) |
| 7220 |
|
| 7221 |
|
| 7222 |
@unittest.skipUnless(sys.platform == 'darwin', 'macOS specific test') |
| 7223 |
class TestMacOSTCPFlags(unittest.TestCase): |
| 7224 |
def test_tcp_keepalive(self): |
| 7225 |
self.assertTrue(socket.TCP_KEEPALIVE) |
| 7226 |
|
| 7227 |
@unittest.skipUnless(hasattr(socket, 'TCP_QUICKACK'), 'need socket.TCP_QUICKACK') |
| 7228 |
class TestQuickackFlag(unittest.TestCase): |
| 7229 |
def check_set_quickack(self, sock): |
| 7230 |
# quickack already true by default on some OS distributions |
| 7231 |
opt = sock.getsockopt(socket.IPPROTO_TCP, socket.TCP_QUICKACK) |
| 7232 |
if opt: |
| 7233 |
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_QUICKACK, 0) |
| 7234 |
|
| 7235 |
opt = sock.getsockopt(socket.IPPROTO_TCP, socket.TCP_QUICKACK) |
| 7236 |
self.assertFalse(opt) |
| 7237 |
|
| 7238 |
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_QUICKACK, 1) |
| 7239 |
|
| 7240 |
opt = sock.getsockopt(socket.IPPROTO_TCP, socket.TCP_QUICKACK) |
| 7241 |
self.assertTrue(opt) |
| 7242 |
|
| 7243 |
def test_set_quickack(self): |
| 7244 |
sock = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM, |
| 7245 |
proto=socket.IPPROTO_TCP) |
| 7246 |
with sock: |
| 7247 |
self.check_set_quickack(sock) |
| 7248 |
|
| 7249 |
|
| 7250 |
@unittest.skipUnless(sys.platform.startswith("win"), "requires Windows") |
| 7251 |
class TestMSWindowsTCPFlags(unittest.TestCase): |
| 7252 |
knownTCPFlags = { |
| 7253 |
# available since long time ago |
| 7254 |
'TCP_MAXSEG', |
| 7255 |
'TCP_NODELAY', |
| 7256 |
# available starting with Windows 10 1607 |
| 7257 |
'TCP_FASTOPEN', |
| 7258 |
# available starting with Windows 10 1703 |
| 7259 |
'TCP_KEEPCNT', |
| 7260 |
# available starting with Windows 10 1709 |
| 7261 |
'TCP_KEEPIDLE', |
| 7262 |
'TCP_KEEPINTVL', |
| 7263 |
# available starting with Windows 7 / Server 2008 R2 |
| 7264 |
'TCP_QUICKACK', |
| 7265 |
} |
| 7266 |
|
| 7267 |
def test_new_tcp_flags(self): |
| 7268 |
provided = [s for s in dir(socket) if s.startswith('TCP')] |
| 7269 |
unknown = [s for s in provided if s not in self.knownTCPFlags] |
| 7270 |
|
| 7271 |
self.assertEqual([], unknown, |
| 7272 |
"New TCP flags were discovered. See bpo-32394 for more information") |
| 7273 |
|
| 7274 |
|
| 7275 |
class CreateServerTest(unittest.TestCase): |
| 7276 |
|
| 7277 |
def test_address(self): |
| 7278 |
port = socket_helper.find_unused_port() |
| 7279 |
with socket.create_server(("127.0.0.1", port)) as sock: |
| 7280 |
self.assertEqual(sock.getsockname()[0], "127.0.0.1") |
| 7281 |
self.assertEqual(sock.getsockname()[1], port) |
| 7282 |
if socket_helper.IPV6_ENABLED: |
| 7283 |
with socket.create_server(("::1", port), |
| 7284 |
family=socket.AF_INET6) as sock: |
| 7285 |
self.assertEqual(sock.getsockname()[0], "::1") |
| 7286 |
self.assertEqual(sock.getsockname()[1], port) |
| 7287 |
|
| 7288 |
def test_family_and_type(self): |
| 7289 |
with socket.create_server(("127.0.0.1", 0)) as sock: |
| 7290 |
self.assertEqual(sock.family, socket.AF_INET) |
| 7291 |
self.assertEqual(sock.type, socket.SOCK_STREAM) |
| 7292 |
if socket_helper.IPV6_ENABLED: |
| 7293 |
with socket.create_server(("::1", 0), family=socket.AF_INET6) as s: |
| 7294 |
self.assertEqual(s.family, socket.AF_INET6) |
| 7295 |
self.assertEqual(sock.type, socket.SOCK_STREAM) |
| 7296 |
|
| 7297 |
def test_reuse_port(self): |
| 7298 |
if not hasattr(socket, "SO_REUSEPORT"): |
| 7299 |
with self.assertRaises(ValueError): |
| 7300 |
socket.create_server(("localhost", 0), reuse_port=True) |
| 7301 |
else: |
| 7302 |
with socket.create_server(("localhost", 0)) as sock: |
| 7303 |
opt = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) |
| 7304 |
self.assertEqual(opt, 0) |
| 7305 |
with socket.create_server(("localhost", 0), reuse_port=True) as sock: |
| 7306 |
opt = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) |
| 7307 |
self.assertNotEqual(opt, 0) |
| 7308 |
|
| 7309 |
@unittest.skipIf(not hasattr(_socket, 'IPPROTO_IPV6') or |
| 7310 |
not hasattr(_socket, 'IPV6_V6ONLY'), |
| 7311 |
"IPV6_V6ONLY option not supported") |
| 7312 |
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test') |
| 7313 |
def test_ipv6_only_default(self): |
| 7314 |
with socket.create_server(("::1", 0), family=socket.AF_INET6) as sock: |
| 7315 |
assert sock.getsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY) |
| 7316 |
|
| 7317 |
@unittest.skipIf(not socket.has_dualstack_ipv6(), |
| 7318 |
"dualstack_ipv6 not supported") |
| 7319 |
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test') |
| 7320 |
def test_dualstack_ipv6_family(self): |
| 7321 |
with socket.create_server(("::1", 0), family=socket.AF_INET6, |
| 7322 |
dualstack_ipv6=True) as sock: |
| 7323 |
self.assertEqual(sock.family, socket.AF_INET6) |
| 7324 |
|
| 7325 |
|
| 7326 |
class CreateServerFunctionalTest(unittest.TestCase): |
| 7327 |
timeout = support.LOOPBACK_TIMEOUT |
| 7328 |
|
| 7329 |
def echo_server(self, sock): |
| 7330 |
def run(sock): |
| 7331 |
with sock: |
| 7332 |
conn, _ = sock.accept() |
| 7333 |
with conn: |
| 7334 |
event.wait(self.timeout) |
| 7335 |
msg = conn.recv(1024) |
| 7336 |
if not msg: |
| 7337 |
return |
| 7338 |
conn.sendall(msg) |
| 7339 |
|
| 7340 |
event = threading.Event() |
| 7341 |
sock.settimeout(self.timeout) |
| 7342 |
thread = threading.Thread(target=run, args=(sock, )) |
| 7343 |
thread.start() |
| 7344 |
self.addCleanup(thread.join, self.timeout) |
| 7345 |
event.set() |
| 7346 |
|
| 7347 |
def echo_client(self, addr, family): |
| 7348 |
with socket.socket(family=family) as sock: |
| 7349 |
sock.settimeout(self.timeout) |
| 7350 |
sock.connect(addr) |
| 7351 |
sock.sendall(b'foo') |
| 7352 |
self.assertEqual(sock.recv(1024), b'foo') |
| 7353 |
|
| 7354 |
def test_tcp4(self): |
| 7355 |
port = socket_helper.find_unused_port() |
| 7356 |
with socket.create_server(("", port)) as sock: |
| 7357 |
self.echo_server(sock) |
| 7358 |
self.echo_client(("127.0.0.1", port), socket.AF_INET) |
| 7359 |
|
| 7360 |
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test') |
| 7361 |
def test_tcp6(self): |
| 7362 |
port = socket_helper.find_unused_port() |
| 7363 |
with socket.create_server(("", port), |
| 7364 |
family=socket.AF_INET6) as sock: |
| 7365 |
self.echo_server(sock) |
| 7366 |
self.echo_client(("::1", port), socket.AF_INET6) |
| 7367 |
|
| 7368 |
# --- dual stack tests |
| 7369 |
|
| 7370 |
@unittest.skipIf(not socket.has_dualstack_ipv6(), |
| 7371 |
"dualstack_ipv6 not supported") |
| 7372 |
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test') |
| 7373 |
def test_dual_stack_client_v4(self): |
| 7374 |
port = socket_helper.find_unused_port() |
| 7375 |
with socket.create_server(("", port), family=socket.AF_INET6, |
| 7376 |
dualstack_ipv6=True) as sock: |
| 7377 |
self.echo_server(sock) |
| 7378 |
self.echo_client(("127.0.0.1", port), socket.AF_INET) |
| 7379 |
|
| 7380 |
@unittest.skipIf(not socket.has_dualstack_ipv6(), |
| 7381 |
"dualstack_ipv6 not supported") |
| 7382 |
@unittest.skipUnless(socket_helper.IPV6_ENABLED, 'IPv6 required for this test') |
| 7383 |
def test_dual_stack_client_v6(self): |
| 7384 |
port = socket_helper.find_unused_port() |
| 7385 |
with socket.create_server(("", port), family=socket.AF_INET6, |
| 7386 |
dualstack_ipv6=True) as sock: |
| 7387 |
self.echo_server(sock) |
| 7388 |
self.echo_client(("::1", port), socket.AF_INET6) |
| 7389 |
|
| 7390 |
@requireAttrs(socket, "send_fds") |
| 7391 |
@requireAttrs(socket, "recv_fds") |
| 7392 |
@requireAttrs(socket, "AF_UNIX") |
| 7393 |
class SendRecvFdsTests(unittest.TestCase): |
| 7394 |
def testSendAndRecvFds(self): |
| 7395 |
def close_pipes(pipes): |
| 7396 |
for fd1, fd2 in pipes: |
| 7397 |
os.close(fd1) |
| 7398 |
os.close(fd2) |
| 7399 |
|
| 7400 |
def close_fds(fds): |
| 7401 |
for fd in fds: |
| 7402 |
os.close(fd) |
| 7403 |
|
| 7404 |
# send 10 file descriptors |
| 7405 |
pipes = [os.pipe() for _ in range(10)] |
| 7406 |
self.addCleanup(close_pipes, pipes) |
| 7407 |
fds = [rfd for rfd, wfd in pipes] |
| 7408 |
|
| 7409 |
# use a UNIX socket pair to exchange file descriptors locally |
| 7410 |
sock1, sock2 = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM) |
| 7411 |
with sock1, sock2: |
| 7412 |
socket.send_fds(sock1, [MSG], fds) |
| 7413 |
# request more data and file descriptors than expected |
| 7414 |
msg, fds2, flags, addr = socket.recv_fds(sock2, len(MSG) * 2, len(fds) * 2) |
| 7415 |
self.addCleanup(close_fds, fds2) |
| 7416 |
|
| 7417 |
self.assertEqual(msg, MSG) |
| 7418 |
self.assertEqual(len(fds2), len(fds)) |
| 7419 |
self.assertEqual(flags, 0) |
| 7420 |
# don't test addr |
| 7421 |
|
| 7422 |
# test that file descriptors are connected |
| 7423 |
for index, fds in enumerate(pipes): |
| 7424 |
rfd, wfd = fds |
| 7425 |
os.write(wfd, str(index).encode()) |
| 7426 |
|
| 7427 |
for index, rfd in enumerate(fds2): |
| 7428 |
data = os.read(rfd, 100) |
| 7429 |
self.assertEqual(data, str(index).encode()) |
| 7430 |
|
| 7431 |
|
| 7432 |
class FreeThreadingTests(unittest.TestCase): |
| 7433 |
|
| 7434 |
def test_close_detach_race(self): |
| 7435 |
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 7436 |
|
| 7437 |
def close(): |
| 7438 |
for _ in range(1000): |
| 7439 |
s.close() |
| 7440 |
|
| 7441 |
def detach(): |
| 7442 |
for _ in range(1000): |
| 7443 |
s.detach() |
| 7444 |
|
| 7445 |
t1 = threading.Thread(target=close) |
| 7446 |
t2 = threading.Thread(target=detach) |
| 7447 |
|
| 7448 |
with threading_helper.start_threads([t1, t2]): |
| 7449 |
pass |
| 7450 |
|
| 7451 |
|
| 7452 |
def setUpModule(): |
| 7453 |
thread_info = threading_helper.threading_setup() |
| 7454 |
unittest.addModuleCleanup(threading_helper.threading_cleanup, *thread_info) |
| 7455 |
|
| 7456 |
|
| 7457 |
if __name__ == "__main__": |
| 7458 |
unittest.main() |