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