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