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