/Lib/test/test_socket.py
Python | 5106 lines | 4716 code | 195 blank | 195 comment | 48 complexity | 8e8c39db65f88ba87ee1f97f7446911d MD5 | raw file
Large files files are truncated, but you can click here to view the full file
1import unittest 2from test import support 3 4import errno 5import io 6import socket 7import select 8import tempfile 9import _testcapi 10import time 11import traceback 12import queue 13import sys 14import os 15import array 16import platform 17import contextlib 18from weakref import proxy 19import signal 20import math 21import pickle 22import struct 23try: 24 import multiprocessing 25except ImportError: 26 multiprocessing = False 27try: 28 import fcntl 29except ImportError: 30 fcntl = None 31 32HOST = support.HOST 33MSG = 'Michael Gilfix was here\u1234\r\n'.encode('utf-8') ## test unicode string and carriage return 34 35try: 36 import _thread as thread 37 import threading 38except ImportError: 39 thread = None 40 threading = None 41 42def _have_socket_can(): 43 """Check whether CAN sockets are supported on this host.""" 44 try: 45 s = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) 46 except (AttributeError, OSError): 47 return False 48 else: 49 s.close() 50 return True 51 52def _have_socket_rds(): 53 """Check whether RDS sockets are supported on this host.""" 54 try: 55 s = socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0) 56 except (AttributeError, OSError): 57 return False 58 else: 59 s.close() 60 return True 61 62HAVE_SOCKET_CAN = _have_socket_can() 63 64HAVE_SOCKET_RDS = _have_socket_rds() 65 66# Size in bytes of the int type 67SIZEOF_INT = array.array("i").itemsize 68 69class SocketTCPTest(unittest.TestCase): 70 71 def setUp(self): 72 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 73 self.port = support.bind_port(self.serv) 74 self.serv.listen(1) 75 76 def tearDown(self): 77 self.serv.close() 78 self.serv = None 79 80class SocketUDPTest(unittest.TestCase): 81 82 def setUp(self): 83 self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 84 self.port = support.bind_port(self.serv) 85 86 def tearDown(self): 87 self.serv.close() 88 self.serv = None 89 90class ThreadSafeCleanupTestCase(unittest.TestCase): 91 """Subclass of unittest.TestCase with thread-safe cleanup methods. 92 93 This subclass protects the addCleanup() and doCleanups() methods 94 with a recursive lock. 95 """ 96 97 if threading: 98 def __init__(self, *args, **kwargs): 99 super().__init__(*args, **kwargs) 100 self._cleanup_lock = threading.RLock() 101 102 def addCleanup(self, *args, **kwargs): 103 with self._cleanup_lock: 104 return super().addCleanup(*args, **kwargs) 105 106 def doCleanups(self, *args, **kwargs): 107 with self._cleanup_lock: 108 return super().doCleanups(*args, **kwargs) 109 110class SocketCANTest(unittest.TestCase): 111 112 """To be able to run this test, a `vcan0` CAN interface can be created with 113 the following commands: 114 # modprobe vcan 115 # ip link add dev vcan0 type vcan 116 # ifconfig vcan0 up 117 """ 118 interface = 'vcan0' 119 bufsize = 128 120 121 """The CAN frame structure is defined in <linux/can.h>: 122 123 struct can_frame { 124 canid_t can_id; /* 32 bit CAN_ID + EFF/RTR/ERR flags */ 125 __u8 can_dlc; /* data length code: 0 .. 8 */ 126 __u8 data[8] __attribute__((aligned(8))); 127 }; 128 """ 129 can_frame_fmt = "=IB3x8s" 130 can_frame_size = struct.calcsize(can_frame_fmt) 131 132 """The Broadcast Management Command frame structure is defined 133 in <linux/can/bcm.h>: 134 135 struct bcm_msg_head { 136 __u32 opcode; 137 __u32 flags; 138 __u32 count; 139 struct timeval ival1, ival2; 140 canid_t can_id; 141 __u32 nframes; 142 struct can_frame frames[0]; 143 } 144 145 `bcm_msg_head` must be 8 bytes aligned because of the `frames` member (see 146 `struct can_frame` definition). Must use native not standard types for packing. 147 """ 148 bcm_cmd_msg_fmt = "@3I4l2I" 149 bcm_cmd_msg_fmt += "x" * (struct.calcsize(bcm_cmd_msg_fmt) % 8) 150 151 def setUp(self): 152 self.s = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) 153 self.addCleanup(self.s.close) 154 try: 155 self.s.bind((self.interface,)) 156 except OSError: 157 self.skipTest('network interface `%s` does not exist' % 158 self.interface) 159 160 161class SocketRDSTest(unittest.TestCase): 162 163 """To be able to run this test, the `rds` kernel module must be loaded: 164 # modprobe rds 165 """ 166 bufsize = 8192 167 168 def setUp(self): 169 self.serv = socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0) 170 self.addCleanup(self.serv.close) 171 try: 172 self.port = support.bind_port(self.serv) 173 except OSError: 174 self.skipTest('unable to bind RDS socket') 175 176 177class ThreadableTest: 178 """Threadable Test class 179 180 The ThreadableTest class makes it easy to create a threaded 181 client/server pair from an existing unit test. To create a 182 new threaded class from an existing unit test, use multiple 183 inheritance: 184 185 class NewClass (OldClass, ThreadableTest): 186 pass 187 188 This class defines two new fixture functions with obvious 189 purposes for overriding: 190 191 clientSetUp () 192 clientTearDown () 193 194 Any new test functions within the class must then define 195 tests in pairs, where the test name is preceeded with a 196 '_' to indicate the client portion of the test. Ex: 197 198 def testFoo(self): 199 # Server portion 200 201 def _testFoo(self): 202 # Client portion 203 204 Any exceptions raised by the clients during their tests 205 are caught and transferred to the main thread to alert 206 the testing framework. 207 208 Note, the server setup function cannot call any blocking 209 functions that rely on the client thread during setup, 210 unless serverExplicitReady() is called just before 211 the blocking call (such as in setting up a client/server 212 connection and performing the accept() in setUp(). 213 """ 214 215 def __init__(self): 216 # Swap the true setup function 217 self.__setUp = self.setUp 218 self.__tearDown = self.tearDown 219 self.setUp = self._setUp 220 self.tearDown = self._tearDown 221 222 def serverExplicitReady(self): 223 """This method allows the server to explicitly indicate that 224 it wants the client thread to proceed. This is useful if the 225 server is about to execute a blocking routine that is 226 dependent upon the client thread during its setup routine.""" 227 self.server_ready.set() 228 229 def _setUp(self): 230 self.server_ready = threading.Event() 231 self.client_ready = threading.Event() 232 self.done = threading.Event() 233 self.queue = queue.Queue(1) 234 self.server_crashed = False 235 236 # Do some munging to start the client test. 237 methodname = self.id() 238 i = methodname.rfind('.') 239 methodname = methodname[i+1:] 240 test_method = getattr(self, '_' + methodname) 241 self.client_thread = thread.start_new_thread( 242 self.clientRun, (test_method,)) 243 244 try: 245 self.__setUp() 246 except: 247 self.server_crashed = True 248 raise 249 finally: 250 self.server_ready.set() 251 self.client_ready.wait() 252 253 def _tearDown(self): 254 self.__tearDown() 255 self.done.wait() 256 257 if self.queue.qsize(): 258 exc = self.queue.get() 259 raise exc 260 261 def clientRun(self, test_func): 262 self.server_ready.wait() 263 self.clientSetUp() 264 self.client_ready.set() 265 if self.server_crashed: 266 self.clientTearDown() 267 return 268 if not hasattr(test_func, '__call__'): 269 raise TypeError("test_func must be a callable function") 270 try: 271 test_func() 272 except BaseException as e: 273 self.queue.put(e) 274 finally: 275 self.clientTearDown() 276 277 def clientSetUp(self): 278 raise NotImplementedError("clientSetUp must be implemented.") 279 280 def clientTearDown(self): 281 self.done.set() 282 thread.exit() 283 284class ThreadedTCPSocketTest(SocketTCPTest, ThreadableTest): 285 286 def __init__(self, methodName='runTest'): 287 SocketTCPTest.__init__(self, methodName=methodName) 288 ThreadableTest.__init__(self) 289 290 def clientSetUp(self): 291 self.cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 292 293 def clientTearDown(self): 294 self.cli.close() 295 self.cli = None 296 ThreadableTest.clientTearDown(self) 297 298class ThreadedUDPSocketTest(SocketUDPTest, ThreadableTest): 299 300 def __init__(self, methodName='runTest'): 301 SocketUDPTest.__init__(self, methodName=methodName) 302 ThreadableTest.__init__(self) 303 304 def clientSetUp(self): 305 self.cli = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 306 307 def clientTearDown(self): 308 self.cli.close() 309 self.cli = None 310 ThreadableTest.clientTearDown(self) 311 312class ThreadedCANSocketTest(SocketCANTest, ThreadableTest): 313 314 def __init__(self, methodName='runTest'): 315 SocketCANTest.__init__(self, methodName=methodName) 316 ThreadableTest.__init__(self) 317 318 def clientSetUp(self): 319 self.cli = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) 320 try: 321 self.cli.bind((self.interface,)) 322 except OSError: 323 # skipTest should not be called here, and will be called in the 324 # server instead 325 pass 326 327 def clientTearDown(self): 328 self.cli.close() 329 self.cli = None 330 ThreadableTest.clientTearDown(self) 331 332class ThreadedRDSSocketTest(SocketRDSTest, ThreadableTest): 333 334 def __init__(self, methodName='runTest'): 335 SocketRDSTest.__init__(self, methodName=methodName) 336 ThreadableTest.__init__(self) 337 338 def clientSetUp(self): 339 self.cli = socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0) 340 try: 341 # RDS sockets must be bound explicitly to send or receive data 342 self.cli.bind((HOST, 0)) 343 self.cli_addr = self.cli.getsockname() 344 except OSError: 345 # skipTest should not be called here, and will be called in the 346 # server instead 347 pass 348 349 def clientTearDown(self): 350 self.cli.close() 351 self.cli = None 352 ThreadableTest.clientTearDown(self) 353 354class SocketConnectedTest(ThreadedTCPSocketTest): 355 """Socket tests for client-server connection. 356 357 self.cli_conn is a client socket connected to the server. The 358 setUp() method guarantees that it is connected to the server. 359 """ 360 361 def __init__(self, methodName='runTest'): 362 ThreadedTCPSocketTest.__init__(self, methodName=methodName) 363 364 def setUp(self): 365 ThreadedTCPSocketTest.setUp(self) 366 # Indicate explicitly we're ready for the client thread to 367 # proceed and then perform the blocking call to accept 368 self.serverExplicitReady() 369 conn, addr = self.serv.accept() 370 self.cli_conn = conn 371 372 def tearDown(self): 373 self.cli_conn.close() 374 self.cli_conn = None 375 ThreadedTCPSocketTest.tearDown(self) 376 377 def clientSetUp(self): 378 ThreadedTCPSocketTest.clientSetUp(self) 379 self.cli.connect((HOST, self.port)) 380 self.serv_conn = self.cli 381 382 def clientTearDown(self): 383 self.serv_conn.close() 384 self.serv_conn = None 385 ThreadedTCPSocketTest.clientTearDown(self) 386 387class SocketPairTest(unittest.TestCase, ThreadableTest): 388 389 def __init__(self, methodName='runTest'): 390 unittest.TestCase.__init__(self, methodName=methodName) 391 ThreadableTest.__init__(self) 392 393 def setUp(self): 394 self.serv, self.cli = socket.socketpair() 395 396 def tearDown(self): 397 self.serv.close() 398 self.serv = None 399 400 def clientSetUp(self): 401 pass 402 403 def clientTearDown(self): 404 self.cli.close() 405 self.cli = None 406 ThreadableTest.clientTearDown(self) 407 408 409# The following classes are used by the sendmsg()/recvmsg() tests. 410# Combining, for instance, ConnectedStreamTestMixin and TCPTestBase 411# gives a drop-in replacement for SocketConnectedTest, but different 412# address families can be used, and the attributes serv_addr and 413# cli_addr will be set to the addresses of the endpoints. 414 415class SocketTestBase(unittest.TestCase): 416 """A base class for socket tests. 417 418 Subclasses must provide methods newSocket() to return a new socket 419 and bindSock(sock) to bind it to an unused address. 420 421 Creates a socket self.serv and sets self.serv_addr to its address. 422 """ 423 424 def setUp(self): 425 self.serv = self.newSocket() 426 self.bindServer() 427 428 def bindServer(self): 429 """Bind server socket and set self.serv_addr to its address.""" 430 self.bindSock(self.serv) 431 self.serv_addr = self.serv.getsockname() 432 433 def tearDown(self): 434 self.serv.close() 435 self.serv = None 436 437 438class SocketListeningTestMixin(SocketTestBase): 439 """Mixin to listen on the server socket.""" 440 441 def setUp(self): 442 super().setUp() 443 self.serv.listen(1) 444 445 446class ThreadedSocketTestMixin(ThreadSafeCleanupTestCase, SocketTestBase, 447 ThreadableTest): 448 """Mixin to add client socket and allow client/server tests. 449 450 Client socket is self.cli and its address is self.cli_addr. See 451 ThreadableTest for usage information. 452 """ 453 454 def __init__(self, *args, **kwargs): 455 super().__init__(*args, **kwargs) 456 ThreadableTest.__init__(self) 457 458 def clientSetUp(self): 459 self.cli = self.newClientSocket() 460 self.bindClient() 461 462 def newClientSocket(self): 463 """Return a new socket for use as client.""" 464 return self.newSocket() 465 466 def bindClient(self): 467 """Bind client socket and set self.cli_addr to its address.""" 468 self.bindSock(self.cli) 469 self.cli_addr = self.cli.getsockname() 470 471 def clientTearDown(self): 472 self.cli.close() 473 self.cli = None 474 ThreadableTest.clientTearDown(self) 475 476 477class ConnectedStreamTestMixin(SocketListeningTestMixin, 478 ThreadedSocketTestMixin): 479 """Mixin to allow client/server stream tests with connected client. 480 481 Server's socket representing connection to client is self.cli_conn 482 and client's connection to server is self.serv_conn. (Based on 483 SocketConnectedTest.) 484 """ 485 486 def setUp(self): 487 super().setUp() 488 # Indicate explicitly we're ready for the client thread to 489 # proceed and then perform the blocking call to accept 490 self.serverExplicitReady() 491 conn, addr = self.serv.accept() 492 self.cli_conn = conn 493 494 def tearDown(self): 495 self.cli_conn.close() 496 self.cli_conn = None 497 super().tearDown() 498 499 def clientSetUp(self): 500 super().clientSetUp() 501 self.cli.connect(self.serv_addr) 502 self.serv_conn = self.cli 503 504 def clientTearDown(self): 505 self.serv_conn.close() 506 self.serv_conn = None 507 super().clientTearDown() 508 509 510class UnixSocketTestBase(SocketTestBase): 511 """Base class for Unix-domain socket tests.""" 512 513 # This class is used for file descriptor passing tests, so we 514 # create the sockets in a private directory so that other users 515 # can't send anything that might be problematic for a privileged 516 # user running the tests. 517 518 def setUp(self): 519 self.dir_path = tempfile.mkdtemp() 520 self.addCleanup(os.rmdir, self.dir_path) 521 super().setUp() 522 523 def bindSock(self, sock): 524 path = tempfile.mktemp(dir=self.dir_path) 525 sock.bind(path) 526 self.addCleanup(support.unlink, path) 527 528class UnixStreamBase(UnixSocketTestBase): 529 """Base class for Unix-domain SOCK_STREAM tests.""" 530 531 def newSocket(self): 532 return socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) 533 534 535class InetTestBase(SocketTestBase): 536 """Base class for IPv4 socket tests.""" 537 538 host = HOST 539 540 def setUp(self): 541 super().setUp() 542 self.port = self.serv_addr[1] 543 544 def bindSock(self, sock): 545 support.bind_port(sock, host=self.host) 546 547class TCPTestBase(InetTestBase): 548 """Base class for TCP-over-IPv4 tests.""" 549 550 def newSocket(self): 551 return socket.socket(socket.AF_INET, socket.SOCK_STREAM) 552 553class UDPTestBase(InetTestBase): 554 """Base class for UDP-over-IPv4 tests.""" 555 556 def newSocket(self): 557 return socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 558 559class SCTPStreamBase(InetTestBase): 560 """Base class for SCTP tests in one-to-one (SOCK_STREAM) mode.""" 561 562 def newSocket(self): 563 return socket.socket(socket.AF_INET, socket.SOCK_STREAM, 564 socket.IPPROTO_SCTP) 565 566 567class Inet6TestBase(InetTestBase): 568 """Base class for IPv6 socket tests.""" 569 570 host = support.HOSTv6 571 572class UDP6TestBase(Inet6TestBase): 573 """Base class for UDP-over-IPv6 tests.""" 574 575 def newSocket(self): 576 return socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) 577 578 579# Test-skipping decorators for use with ThreadableTest. 580 581def skipWithClientIf(condition, reason): 582 """Skip decorated test if condition is true, add client_skip decorator. 583 584 If the decorated object is not a class, sets its attribute 585 "client_skip" to a decorator which will return an empty function 586 if the test is to be skipped, or the original function if it is 587 not. This can be used to avoid running the client part of a 588 skipped test when using ThreadableTest. 589 """ 590 def client_pass(*args, **kwargs): 591 pass 592 def skipdec(obj): 593 retval = unittest.skip(reason)(obj) 594 if not isinstance(obj, type): 595 retval.client_skip = lambda f: client_pass 596 return retval 597 def noskipdec(obj): 598 if not (isinstance(obj, type) or hasattr(obj, "client_skip")): 599 obj.client_skip = lambda f: f 600 return obj 601 return skipdec if condition else noskipdec 602 603 604def requireAttrs(obj, *attributes): 605 """Skip decorated test if obj is missing any of the given attributes. 606 607 Sets client_skip attribute as skipWithClientIf() does. 608 """ 609 missing = [name for name in attributes if not hasattr(obj, name)] 610 return skipWithClientIf( 611 missing, "don't have " + ", ".join(name for name in missing)) 612 613 614def requireSocket(*args): 615 """Skip decorated test if a socket cannot be created with given arguments. 616 617 When an argument is given as a string, will use the value of that 618 attribute of the socket module, or skip the test if it doesn't 619 exist. Sets client_skip attribute as skipWithClientIf() does. 620 """ 621 err = None 622 missing = [obj for obj in args if 623 isinstance(obj, str) and not hasattr(socket, obj)] 624 if missing: 625 err = "don't have " + ", ".join(name for name in missing) 626 else: 627 callargs = [getattr(socket, obj) if isinstance(obj, str) else obj 628 for obj in args] 629 try: 630 s = socket.socket(*callargs) 631 except OSError as e: 632 # XXX: check errno? 633 err = str(e) 634 else: 635 s.close() 636 return skipWithClientIf( 637 err is not None, 638 "can't create socket({0}): {1}".format( 639 ", ".join(str(o) for o in args), err)) 640 641 642####################################################################### 643## Begin Tests 644 645class GeneralModuleTests(unittest.TestCase): 646 647 def test_repr(self): 648 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 649 with s: 650 self.assertIn('fd=%i' % s.fileno(), repr(s)) 651 self.assertIn('family=%s' % socket.AF_INET, repr(s)) 652 self.assertIn('type=%s' % socket.SOCK_STREAM, repr(s)) 653 self.assertIn('proto=0', repr(s)) 654 self.assertNotIn('raddr', repr(s)) 655 s.bind(('127.0.0.1', 0)) 656 self.assertIn('laddr', repr(s)) 657 self.assertIn(str(s.getsockname()), repr(s)) 658 self.assertIn('[closed]', repr(s)) 659 self.assertNotIn('laddr', repr(s)) 660 661 def test_weakref(self): 662 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 663 p = proxy(s) 664 self.assertEqual(p.fileno(), s.fileno()) 665 s.close() 666 s = None 667 try: 668 p.fileno() 669 except ReferenceError: 670 pass 671 else: 672 self.fail('Socket proxy still exists') 673 674 def testSocketError(self): 675 # Testing socket module exceptions 676 msg = "Error raising socket exception (%s)." 677 with self.assertRaises(OSError, msg=msg % 'OSError'): 678 raise OSError 679 with self.assertRaises(OSError, msg=msg % 'socket.herror'): 680 raise socket.herror 681 with self.assertRaises(OSError, msg=msg % 'socket.gaierror'): 682 raise socket.gaierror 683 684 def testSendtoErrors(self): 685 # Testing that sendto doens't masks failures. See #10169. 686 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 687 self.addCleanup(s.close) 688 s.bind(('', 0)) 689 sockname = s.getsockname() 690 # 2 args 691 with self.assertRaises(TypeError) as cm: 692 s.sendto('\u2620', sockname) 693 self.assertEqual(str(cm.exception), 694 "'str' does not support the buffer interface") 695 with self.assertRaises(TypeError) as cm: 696 s.sendto(5j, sockname) 697 self.assertEqual(str(cm.exception), 698 "'complex' does not support the buffer interface") 699 with self.assertRaises(TypeError) as cm: 700 s.sendto(b'foo', None) 701 self.assertIn('not NoneType',str(cm.exception)) 702 # 3 args 703 with self.assertRaises(TypeError) as cm: 704 s.sendto('\u2620', 0, sockname) 705 self.assertEqual(str(cm.exception), 706 "'str' does not support the buffer interface") 707 with self.assertRaises(TypeError) as cm: 708 s.sendto(5j, 0, sockname) 709 self.assertEqual(str(cm.exception), 710 "'complex' does not support the buffer interface") 711 with self.assertRaises(TypeError) as cm: 712 s.sendto(b'foo', 0, None) 713 self.assertIn('not NoneType', str(cm.exception)) 714 with self.assertRaises(TypeError) as cm: 715 s.sendto(b'foo', 'bar', sockname) 716 self.assertIn('an integer is required', str(cm.exception)) 717 with self.assertRaises(TypeError) as cm: 718 s.sendto(b'foo', None, None) 719 self.assertIn('an integer is required', str(cm.exception)) 720 # wrong number of args 721 with self.assertRaises(TypeError) as cm: 722 s.sendto(b'foo') 723 self.assertIn('(1 given)', str(cm.exception)) 724 with self.assertRaises(TypeError) as cm: 725 s.sendto(b'foo', 0, sockname, 4) 726 self.assertIn('(4 given)', str(cm.exception)) 727 728 def testCrucialConstants(self): 729 # Testing for mission critical constants 730 socket.AF_INET 731 socket.SOCK_STREAM 732 socket.SOCK_DGRAM 733 socket.SOCK_RAW 734 socket.SOCK_RDM 735 socket.SOCK_SEQPACKET 736 socket.SOL_SOCKET 737 socket.SO_REUSEADDR 738 739 def testHostnameRes(self): 740 # Testing hostname resolution mechanisms 741 hostname = socket.gethostname() 742 try: 743 ip = socket.gethostbyname(hostname) 744 except OSError: 745 # Probably name lookup wasn't set up right; skip this test 746 self.skipTest('name lookup failure') 747 self.assertTrue(ip.find('.') >= 0, "Error resolving host to ip.") 748 try: 749 hname, aliases, ipaddrs = socket.gethostbyaddr(ip) 750 except OSError: 751 # Probably a similar problem as above; skip this test 752 self.skipTest('name lookup failure') 753 all_host_names = [hostname, hname] + aliases 754 fqhn = socket.getfqdn(ip) 755 if not fqhn in all_host_names: 756 self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names))) 757 758 def test_host_resolution(self): 759 for addr in ['0.1.1.~1', '1+.1.1.1', '::1q', '::1::2', 760 '1:1:1:1:1:1:1:1:1']: 761 self.assertRaises(OSError, socket.gethostbyname, addr) 762 self.assertRaises(OSError, socket.gethostbyaddr, addr) 763 764 for addr in [support.HOST, '10.0.0.1', '255.255.255.255']: 765 self.assertEqual(socket.gethostbyname(addr), addr) 766 767 # we don't test support.HOSTv6 because there's a chance it doesn't have 768 # a matching name entry (e.g. 'ip6-localhost') 769 for host in [support.HOST]: 770 self.assertIn(host, socket.gethostbyaddr(host)[2]) 771 772 @unittest.skipUnless(hasattr(socket, 'sethostname'), "test needs socket.sethostname()") 773 @unittest.skipUnless(hasattr(socket, 'gethostname'), "test needs socket.gethostname()") 774 def test_sethostname(self): 775 oldhn = socket.gethostname() 776 try: 777 socket.sethostname('new') 778 except OSError as e: 779 if e.errno == errno.EPERM: 780 self.skipTest("test should be run as root") 781 else: 782 raise 783 try: 784 # running test as root! 785 self.assertEqual(socket.gethostname(), 'new') 786 # Should work with bytes objects too 787 socket.sethostname(b'bar') 788 self.assertEqual(socket.gethostname(), 'bar') 789 finally: 790 socket.sethostname(oldhn) 791 792 @unittest.skipUnless(hasattr(socket, 'if_nameindex'), 793 'socket.if_nameindex() not available.') 794 def testInterfaceNameIndex(self): 795 interfaces = socket.if_nameindex() 796 for index, name in interfaces: 797 self.assertIsInstance(index, int) 798 self.assertIsInstance(name, str) 799 # interface indices are non-zero integers 800 self.assertGreater(index, 0) 801 _index = socket.if_nametoindex(name) 802 self.assertIsInstance(_index, int) 803 self.assertEqual(index, _index) 804 _name = socket.if_indextoname(index) 805 self.assertIsInstance(_name, str) 806 self.assertEqual(name, _name) 807 808 @unittest.skipUnless(hasattr(socket, 'if_nameindex'), 809 'socket.if_nameindex() not available.') 810 def testInvalidInterfaceNameIndex(self): 811 # test nonexistent interface index/name 812 self.assertRaises(OSError, socket.if_indextoname, 0) 813 self.assertRaises(OSError, socket.if_nametoindex, '_DEADBEEF') 814 # test with invalid values 815 self.assertRaises(TypeError, socket.if_nametoindex, 0) 816 self.assertRaises(TypeError, socket.if_indextoname, '_DEADBEEF') 817 818 @unittest.skipUnless(hasattr(sys, 'getrefcount'), 819 'test needs sys.getrefcount()') 820 def testRefCountGetNameInfo(self): 821 # Testing reference count for getnameinfo 822 try: 823 # On some versions, this loses a reference 824 orig = sys.getrefcount(__name__) 825 socket.getnameinfo(__name__,0) 826 except TypeError: 827 if sys.getrefcount(__name__) != orig: 828 self.fail("socket.getnameinfo loses a reference") 829 830 def testInterpreterCrash(self): 831 # Making sure getnameinfo doesn't crash the interpreter 832 try: 833 # On some versions, this crashes the interpreter. 834 socket.getnameinfo(('x', 0, 0, 0), 0) 835 except OSError: 836 pass 837 838 def testNtoH(self): 839 # This just checks that htons etc. are their own inverse, 840 # when looking at the lower 16 or 32 bits. 841 sizes = {socket.htonl: 32, socket.ntohl: 32, 842 socket.htons: 16, socket.ntohs: 16} 843 for func, size in sizes.items(): 844 mask = (1<<size) - 1 845 for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210): 846 self.assertEqual(i & mask, func(func(i&mask)) & mask) 847 848 swapped = func(mask) 849 self.assertEqual(swapped & mask, mask) 850 self.assertRaises(OverflowError, func, 1<<34) 851 852 def testNtoHErrors(self): 853 good_values = [ 1, 2, 3, 1, 2, 3 ] 854 bad_values = [ -1, -2, -3, -1, -2, -3 ] 855 for k in good_values: 856 socket.ntohl(k) 857 socket.ntohs(k) 858 socket.htonl(k) 859 socket.htons(k) 860 for k in bad_values: 861 self.assertRaises(OverflowError, socket.ntohl, k) 862 self.assertRaises(OverflowError, socket.ntohs, k) 863 self.assertRaises(OverflowError, socket.htonl, k) 864 self.assertRaises(OverflowError, socket.htons, k) 865 866 def testGetServBy(self): 867 eq = self.assertEqual 868 # Find one service that exists, then check all the related interfaces. 869 # I've ordered this by protocols that have both a tcp and udp 870 # protocol, at least for modern Linuxes. 871 if (sys.platform.startswith(('freebsd', 'netbsd')) 872 or sys.platform in ('linux', 'darwin')): 873 # avoid the 'echo' service on this platform, as there is an 874 # assumption breaking non-standard port/protocol entry 875 services = ('daytime', 'qotd', 'domain') 876 else: 877 services = ('echo', 'daytime', 'domain') 878 for service in services: 879 try: 880 port = socket.getservbyname(service, 'tcp') 881 break 882 except OSError: 883 pass 884 else: 885 raise OSError 886 # Try same call with optional protocol omitted 887 port2 = socket.getservbyname(service) 888 eq(port, port2) 889 # Try udp, but don't barf if it doesn't exist 890 try: 891 udpport = socket.getservbyname(service, 'udp') 892 except OSError: 893 udpport = None 894 else: 895 eq(udpport, port) 896 # Now make sure the lookup by port returns the same service name 897 eq(socket.getservbyport(port2), service) 898 eq(socket.getservbyport(port, 'tcp'), service) 899 if udpport is not None: 900 eq(socket.getservbyport(udpport, 'udp'), service) 901 # Make sure getservbyport does not accept out of range ports. 902 self.assertRaises(OverflowError, socket.getservbyport, -1) 903 self.assertRaises(OverflowError, socket.getservbyport, 65536) 904 905 def testDefaultTimeout(self): 906 # Testing default timeout 907 # The default timeout should initially be None 908 self.assertEqual(socket.getdefaulttimeout(), None) 909 s = socket.socket() 910 self.assertEqual(s.gettimeout(), None) 911 s.close() 912 913 # Set the default timeout to 10, and see if it propagates 914 socket.setdefaulttimeout(10) 915 self.assertEqual(socket.getdefaulttimeout(), 10) 916 s = socket.socket() 917 self.assertEqual(s.gettimeout(), 10) 918 s.close() 919 920 # Reset the default timeout to None, and see if it propagates 921 socket.setdefaulttimeout(None) 922 self.assertEqual(socket.getdefaulttimeout(), None) 923 s = socket.socket() 924 self.assertEqual(s.gettimeout(), None) 925 s.close() 926 927 # Check that setting it to an invalid value raises ValueError 928 self.assertRaises(ValueError, socket.setdefaulttimeout, -1) 929 930 # Check that setting it to an invalid type raises TypeError 931 self.assertRaises(TypeError, socket.setdefaulttimeout, "spam") 932 933 @unittest.skipUnless(hasattr(socket, 'inet_aton'), 934 'test needs socket.inet_aton()') 935 def testIPv4_inet_aton_fourbytes(self): 936 # Test that issue1008086 and issue767150 are fixed. 937 # It must return 4 bytes. 938 self.assertEqual(b'\x00'*4, socket.inet_aton('0.0.0.0')) 939 self.assertEqual(b'\xff'*4, socket.inet_aton('255.255.255.255')) 940 941 @unittest.skipUnless(hasattr(socket, 'inet_pton'), 942 'test needs socket.inet_pton()') 943 def testIPv4toString(self): 944 from socket import inet_aton as f, inet_pton, AF_INET 945 g = lambda a: inet_pton(AF_INET, a) 946 947 assertInvalid = lambda func,a: self.assertRaises( 948 (OSError, ValueError), func, a 949 ) 950 951 self.assertEqual(b'\x00\x00\x00\x00', f('0.0.0.0')) 952 self.assertEqual(b'\xff\x00\xff\x00', f('255.0.255.0')) 953 self.assertEqual(b'\xaa\xaa\xaa\xaa', f('170.170.170.170')) 954 self.assertEqual(b'\x01\x02\x03\x04', f('1.2.3.4')) 955 self.assertEqual(b'\xff\xff\xff\xff', f('255.255.255.255')) 956 assertInvalid(f, '0.0.0.') 957 assertInvalid(f, '300.0.0.0') 958 assertInvalid(f, 'a.0.0.0') 959 assertInvalid(f, '1.2.3.4.5') 960 assertInvalid(f, '::1') 961 962 self.assertEqual(b'\x00\x00\x00\x00', g('0.0.0.0')) 963 self.assertEqual(b'\xff\x00\xff\x00', g('255.0.255.0')) 964 self.assertEqual(b'\xaa\xaa\xaa\xaa', g('170.170.170.170')) 965 self.assertEqual(b'\xff\xff\xff\xff', g('255.255.255.255')) 966 assertInvalid(g, '0.0.0.') 967 assertInvalid(g, '300.0.0.0') 968 assertInvalid(g, 'a.0.0.0') 969 assertInvalid(g, '1.2.3.4.5') 970 assertInvalid(g, '::1') 971 972 @unittest.skipUnless(hasattr(socket, 'inet_pton'), 973 'test needs socket.inet_pton()') 974 def testIPv6toString(self): 975 try: 976 from socket import inet_pton, AF_INET6, has_ipv6 977 if not has_ipv6: 978 self.skipTest('IPv6 not available') 979 except ImportError: 980 self.skipTest('could not import needed symbols from socket') 981 982 if sys.platform == "win32": 983 try: 984 inet_pton(AF_INET6, '::') 985 except OSError as e: 986 if e.winerror == 10022: 987 self.skipTest('IPv6 might not be supported') 988 989 f = lambda a: inet_pton(AF_INET6, a) 990 assertInvalid = lambda a: self.assertRaises( 991 (OSError, ValueError), f, a 992 ) 993 994 self.assertEqual(b'\x00' * 16, f('::')) 995 self.assertEqual(b'\x00' * 16, f('0::0')) 996 self.assertEqual(b'\x00\x01' + b'\x00' * 14, f('1::')) 997 self.assertEqual( 998 b'\x45\xef\x76\xcb\x00\x1a\x56\xef\xaf\xeb\x0b\xac\x19\x24\xae\xae', 999 f('45ef:76cb:1a:56ef:afeb:bac:1924:aeae') 1000 ) 1001 self.assertEqual( 1002 b'\xad\x42\x0a\xbc' + b'\x00' * 4 + b'\x01\x27\x00\x00\x02\x54\x00\x02', 1003 f('ad42:abc::127:0:254:2') 1004 ) 1005 self.assertEqual(b'\x00\x12\x00\x0a' + b'\x00' * 12, f('12:a::')) 1006 assertInvalid('0x20::') 1007 assertInvalid(':::') 1008 assertInvalid('::0::') 1009 assertInvalid('1::abc::') 1010 assertInvalid('1::abc::def') 1011 assertInvalid('1:2:3:4:5:6:') 1012 assertInvalid('1:2:3:4:5:6') 1013 assertInvalid('1:2:3:4:5:6:7:8:') 1014 assertInvalid('1:2:3:4:5:6:7:8:0') 1015 1016 self.assertEqual(b'\x00' * 12 + b'\xfe\x2a\x17\x40', 1017 f('::254.42.23.64') 1018 ) 1019 self.assertEqual( 1020 b'\x00\x42' + b'\x00' * 8 + b'\xa2\x9b\xfe\x2a\x17\x40', 1021 f('42::a29b:254.42.23.64') 1022 ) 1023 self.assertEqual( 1024 b'\x00\x42\xa8\xb9\x00\x00\x00\x02\xff\xff\xa2\x9b\xfe\x2a\x17\x40', 1025 f('42:a8b9:0:2:ffff:a29b:254.42.23.64') 1026 ) 1027 assertInvalid('255.254.253.252') 1028 assertInvalid('1::260.2.3.0') 1029 assertInvalid('1::0.be.e.0') 1030 assertInvalid('1:2:3:4:5:6:7:1.2.3.4') 1031 assertInvalid('::1.2.3.4:0') 1032 assertInvalid('0.100.200.0:3:4:5:6:7:8') 1033 1034 @unittest.skipUnless(hasattr(socket, 'inet_ntop'), 1035 'test needs socket.inet_ntop()') 1036 def testStringToIPv4(self): 1037 from socket import inet_ntoa as f, inet_ntop, AF_INET 1038 g = lambda a: inet_ntop(AF_INET, a) 1039 assertInvalid = lambda func,a: self.assertRaises( 1040 (OSError, ValueError), func, a 1041 ) 1042 1043 self.assertEqual('1.0.1.0', f(b'\x01\x00\x01\x00')) 1044 self.assertEqual('170.85.170.85', f(b'\xaa\x55\xaa\x55')) 1045 self.assertEqual('255.255.255.255', f(b'\xff\xff\xff\xff')) 1046 self.assertEqual('1.2.3.4', f(b'\x01\x02\x03\x04')) 1047 assertInvalid(f, b'\x00' * 3) 1048 assertInvalid(f, b'\x00' * 5) 1049 assertInvalid(f, b'\x00' * 16) 1050 1051 self.assertEqual('1.0.1.0', g(b'\x01\x00\x01\x00')) 1052 self.assertEqual('170.85.170.85', g(b'\xaa\x55\xaa\x55')) 1053 self.assertEqual('255.255.255.255', g(b'\xff\xff\xff\xff')) 1054 assertInvalid(g, b'\x00' * 3) 1055 assertInvalid(g, b'\x00' * 5) 1056 assertInvalid(g, b'\x00' * 16) 1057 1058 @unittest.skipUnless(hasattr(socket, 'inet_ntop'), 1059 'test needs socket.inet_ntop()') 1060 def testStringToIPv6(self): 1061 try: 1062 from socket import inet_ntop, AF_INET6, has_ipv6 1063 if not has_ipv6: 1064 self.skipTest('IPv6 not available') 1065 except ImportError: 1066 self.skipTest('could not import needed symbols from socket') 1067 1068 if sys.platform == "win32": 1069 try: 1070 inet_ntop(AF_INET6, b'\x00' * 16) 1071 except OSError as e: 1072 if e.winerror == 10022: 1073 self.skipTest('IPv6 might not be supported') 1074 1075 f = lambda a: inet_ntop(AF_INET6, a) 1076 assertInvalid = lambda a: self.assertRaises( 1077 (OSError, ValueError), f, a 1078 ) 1079 1080 self.assertEqual('::', f(b'\x00' * 16)) 1081 self.assertEqual('::1', f(b'\x00' * 15 + b'\x01')) 1082 self.assertEqual( 1083 'aef:b01:506:1001:ffff:9997:55:170', 1084 f(b'\x0a\xef\x0b\x01\x05\x06\x10\x01\xff\xff\x99\x97\x00\x55\x01\x70') 1085 ) 1086 1087 assertInvalid(b'\x12' * 15) 1088 assertInvalid(b'\x12' * 17) 1089 assertInvalid(b'\x12' * 4) 1090 1091 # XXX The following don't test module-level functionality... 1092 1093 def testSockName(self): 1094 # Testing getsockname() 1095 port = support.find_unused_port() 1096 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 1097 self.addCleanup(sock.close) 1098 sock.bind(("0.0.0.0", port)) 1099 name = sock.getsockname() 1100 # XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate 1101 # it reasonable to get the host's addr in addition to 0.0.0.0. 1102 # At least for eCos. This is required for the S/390 to pass. 1103 try: 1104 my_ip_addr = socket.gethostbyname(socket.gethostname()) 1105 except OSError: 1106 # Probably name lookup wasn't set up right; skip this test 1107 self.skipTest('name lookup failure') 1108 self.assertIn(name[0], ("0.0.0.0", my_ip_addr), '%s invalid' % name[0]) 1109 self.assertEqual(name[1], port) 1110 1111 def testGetSockOpt(self): 1112 # Testing getsockopt() 1113 # We know a socket should start without reuse==0 1114 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 1115 self.addCleanup(sock.close) 1116 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) 1117 self.assertFalse(reuse != 0, "initial mode is reuse") 1118 1119 def testSetSockOpt(self): 1120 # Testing setsockopt() 1121 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 1122 self.addCleanup(sock.close) 1123 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 1124 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) 1125 self.assertFalse(reuse == 0, "failed to set reuse mode") 1126 1127 def testSendAfterClose(self): 1128 # testing send() after close() with timeout 1129 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 1130 sock.settimeout(1) 1131 sock.close() 1132 self.assertRaises(OSError, sock.send, b"spam") 1133 1134 def testNewAttributes(self): 1135 # testing .family, .type and .protocol 1136 1137 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 1138 self.assertEqual(sock.family, socket.AF_INET) 1139 if hasattr(socket, 'SOCK_CLOEXEC'): 1140 self.assertIn(sock.type, 1141 (socket.SOCK_STREAM | socket.SOCK_CLOEXEC, 1142 socket.SOCK_STREAM)) 1143 else: 1144 self.assertEqual(sock.type, socket.SOCK_STREAM) 1145 self.assertEqual(sock.proto, 0) 1146 sock.close() 1147 1148 def test_getsockaddrarg(self): 1149 host = '0.0.0.0' 1150 port = support.find_unused_port() 1151 big_port = port + 65536 1152 neg_port = port - 65536 1153 sock = socket.socket() 1154 try: 1155 self.assertRaises(OverflowError, sock.bind, (host, big_port)) 1156 self.assertRaises(OverflowError, sock.bind, (host, neg_port)) 1157 sock.bind((host, port)) 1158 finally: 1159 sock.close() 1160 1161 @unittest.skipUnless(os.name == "nt", "Windows specific") 1162 def test_sock_ioctl(self): 1163 self.assertTrue(hasattr(socket.socket, 'ioctl')) 1164 self.assertTrue(hasattr(socket, 'SIO_RCVALL')) 1165 self.assertTrue(hasattr(socket, 'RCVALL_ON')) 1166 self.assertTrue(hasattr(socket, 'RCVALL_OFF')) 1167 self.assertTrue(hasattr(socket, 'SIO_KEEPALIVE_VALS')) 1168 s = socket.socket() 1169 self.addCleanup(s.close) 1170 self.assertRaises(ValueError, s.ioctl, -1, None) 1171 s.ioctl(socket.SIO_KEEPALIVE_VALS, (1, 100, 100)) 1172 1173 def testGetaddrinfo(self): 1174 try: 1175 socket.getaddrinfo('localhost', 80) 1176 except socket.gaierror as err: 1177 if err.errno == socket.EAI_SERVICE: 1178 # see http://bugs.python.org/issue1282647 1179 self.skipTest("buggy libc version") 1180 raise 1181 # len of every sequence is supposed to be == 5 1182 for info in socket.getaddrinfo(HOST, None): 1183 self.assertEqual(len(info), 5) 1184 # host can be a domain name, a string representation of an 1185 # IPv4/v6 address or None 1186 socket.getaddrinfo('localhost', 80) 1187 socket.getaddrinfo('127.0.0.1', 80) 1188 socket.getaddrinfo(None, 80) 1189 if support.IPV6_ENABLED: 1190 socket.getaddrinfo('::1', 80) 1191 # port can be a string service name such as "http", a numeric 1192 # port number or None 1193 socket.getaddrinfo(HOST, "http") 1194 socket.getaddrinfo(HOST, 80) 1195 socket.getaddrinfo(HOST, None) 1196 # test family and socktype filters 1197 infos = socket.getaddrinfo(HOST, 80, socket.AF_INET, socket.SOCK_STREAM) 1198 for family, type, _, _, _ in infos: 1199 self.assertEqual(family, socket.AF_INET) 1200 self.assertEqual(str(family), 'AddressFamily.AF_INET') 1201 self.assertEqual(type, socket.SOCK_STREAM) 1202 self.assertEqual(str(type), 'SocketType.SOCK_STREAM') 1203 infos = socket.getaddrinfo(HOST, None, 0, socket.SOCK_STREAM) 1204 for _, socktype, _, _, _ in infos: 1205 self.assertEqual(socktype, socket.SOCK_STREAM) 1206 # test proto and flags arguments 1207 socket.getaddrinfo(HOST, None, 0, 0, socket.SOL_TCP) 1208 socket.getaddrinfo(HOST, None, 0, 0, 0, socket.AI_PASSIVE) 1209 # a server willing to support both IPv4 and IPv6 will 1210 # usually do this 1211 socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, 1212 socket.AI_PASSIVE) 1213 # test keyword arguments 1214 a = socket.getaddrinfo(HOST, None) 1215 b = socket.getaddrinfo(host=HOST, port=None) 1216 self.assertEqual(a, b) 1217 a = socket.getaddrinfo(HOST, None, socket.AF_INET) 1218 b = socket.getaddrinfo(HOST, None, family=socket.AF_INET) 1219 self.assertEqual(a, b) 1220 a = socket.getaddrinfo(HOST, None, 0, socket.SOCK_STREAM) 1221 b = socket.getaddrinfo(HOST, None, type=socket.SOCK_STREAM) 1222 self.assertEqual(a, b) 1223 a = socket.getaddrinfo(HOST, None, 0, 0, socket.SOL_TCP) 1224 b = socket.getaddrinfo(HOST, None, proto=socket.SOL_TCP) 1225 self.assertEqual(a, b) 1226 a = socket.getaddrinfo(HOST, None, 0, 0, 0, socket.AI_PASSIVE) 1227 b = socket.getaddrinfo(HOST, None, flags=socket.AI_PASSIVE) 1228 self.assertEqual(a, b) 1229 a = socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, 1230 socket.AI_PASSIVE) 1231 b = socket.getaddrinfo(host=None, port=0, family=socket.AF_UNSPEC, 1232 type=socket.SOCK_STREAM, proto=0, 1233 flags=socket.AI_PASSIVE) 1234 self.assertEqual(a, b) 1235 # Issue #6697. 1236 self.assertRaises(UnicodeEncodeError, socket.getaddrinfo, 'localhost', '\uD800') 1237 1238 # Issue 17269 1239 if hasattr(socket, 'AI_NUMERICSERV'): 1240 socket.getaddrinfo("localhost", None, 0, 0, 0, socket.AI_NUMERICSERV) 1241 1242 def test_getnameinfo(self): 1243 # only IP addresses are allowed 1244 self.assertRaises(OSError, socket.getnameinfo, ('mail.python.org',0), 0) 1245 1246 @unittest.skipUnless(support.is_resource_enabled('network'), 1247 'network is not enabled') 1248 def test_idna(self): 1249 # Check for internet access before running test (issue #12804). 1250 try: 1251 socket.gethostbyname('python.org') 1252 except socket.gaierror as e: 1253 if e.errno == socket.EAI_NODATA: 1254 self.skipTest('internet access required for this test') 1255 # these should all be successful 1256 socket.gethostbyname('испытание.python.org') 1257 socket.gethostbyname_ex('испытание.python.org') 1258 socket.getaddrinfo('испытание.python.org',0,socket.AF_UNSPEC,socket.SOCK_STREAM) 1259 # this may not work if the forward lookup choses the IPv6 address, as that doesn't 1260 # have a reverse entry yet 1261 # socket.gethostbyaddr('испытание.python.org') 1262 1263 def check_sendall_interrupted(self, with_timeout): 1264 # socketpair() is not stricly required, but it makes things easier. 1265 if not hasattr(signal, 'alarm') or not hasattr(socket, 'socketpair'): 1266 self.skipTest("signal.alarm and socket.socketpair required for this test") 1267 # Our signal handlers clobber the C errno by calling a math function 1268 # with an invalid domain value. 1269 def ok_handler(*args): 1270 self.assertRaises(ValueError, math.acosh, 0) 1271 def raising_handler(*args): 1272 self.assertRaises(ValueError, math.acosh, 0) 1273 1 // 0 1274 c, s = socket.socketpair() 1275 old_alarm = signal.signal(signal.SIGALRM, raising_handler) 1276 try: 1277 if with_timeout: 1278 # Just above the one second minimum for signal.alarm 1279 c.settimeout(1.5) 1280 with self.assertRaises(ZeroDivisionError): 1281 signal.alarm(1) 1282 c.sendall(b"x" * support.SOCK_MAX_SIZE) 1283 if with_timeout: 1284 signal.signal(signal.SIGALRM, ok_handler) 1285 signal.alarm(1) 1286 self.assertRaises(socket.timeout, c.sendall, 1287 b"x" * support.SOCK_MAX_SIZE) 1288 finally: 1289 signal.alarm(0) 1290 signal.signal(signal.SIGALRM, old_alarm) 1291 c.close() 1292 s.close() 1293 1294 def test_sendall_interrupted(self): 1295 self.check_sendall_interrupted(False) 1296 1297 def test_sendall_interrupted_with_timeout(self): 1298 self.check_sendall_interrupted(True) 1299 1300 def test_dealloc_warn(self): 1301 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 1302 r = repr(sock) 1303 with self.assertWarns(ResourceWarning) as cm: 1304 sock = None 1305 support.gc_collect() 1306 self.assertIn(r, str(cm.warning.args[0])) 1307 # An open socket file object gets dereferenced after the socket 1308 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 1309 f = sock.makefile('rb') 1310 r = repr(sock) 1311 sock = None 1312 support.gc_collect() 1313 with self.assertWarns(ResourceWarning): 1314 f = None 1315 support.gc_collect() 1316 1317 def test_name_closed_socketio(self): 1318 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: 1319 fp = sock.makefile("rb") 1320 fp.close() 1321 self.assertEqual(repr(fp), "<_io.BufferedReader name=-1>") 1322 1323 def test_unusable_closed_socketio(self): 1324 with socket.socket() as sock: 1325 fp = sock.makefile("rb", buffering=0) 1326 self.assertTrue(fp.readable()) 1327 self.assertFalse(fp.writable()) 1328 self.assertFalse(fp.seekable()) 1329 fp.close() 1330 self.assertRaises(ValueError, fp.readable) 1331 self.assertRaises(ValueError, fp.writable) 1332 self.assertRaises(ValueError, fp.seekable) 1333 1334 def test_pickle(self): 1335 sock = socket.socket() 1336 with sock: 1337 for protocol in range(pickle.HIGHEST_PROTOCOL + 1): 1338 self.assertRaises(TypeError, pickle.dumps, sock, protocol) 1339 1340 def test_listen_backlog(self): 1341 for backlog in 0, -1: 1342 srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 1343 srv.bind((HOST, 0)) 1344 srv.listen(backlog) 1345 srv.close() 1346 1347 # Issue 15989 1348 srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 1349 srv.bind((HOST, 0)) 1350 self.assertRaises(OverflowError, srv.listen, _testcapi.INT_MAX + 1) 1351 srv.close() 1352 1353 @unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.') 1354 def test_flowinfo(self): 1355 self.assertRaises(OverflowError, socket.getnameinfo, 1356 (support.HOSTv6, 0, 0xffffffff), 0) 1357 with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s: 1358 self.assertRaises(OverflowError, s.bind, (support.HOSTv6, 0, -10)) 1359 1360 def test_str_for_enums(self): 1361 # Make sure that the AF_* and SOCK_* constants have enum-like string 1362 # reprs. 1363 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: 1364 self.assertEqual(str(s.family), 'AddressFamily.AF_INET') 1365 self.assertEqual(str(s.type), 'SocketType.SOCK_STREAM') 1366 1367 @unittest.skipIf(os.name == 'nt', 'Will not work on Windows') 1368 def test_uknown_socket_family_repr(self): 1369 # Test that when created with a family that's not one of the known 1370 # AF_*/SOCK_* constants, socket.family just returns the number. 1371 # 1372 # To do this we fool socket.socket into believing it already has an 1373 # open fd because on this path it doesn't actually verify the family and 1374 # type and populates the socket object. 1375 # 1376 # On Windows this trick won't work, so the test is skipped. 1377 fd, _ = tempfile.mkstemp() 1378 with socket.socket(family=42424, t…
Large files files are truncated, but you can click here to view the full file