Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(169900)

Delta Between Two Patch Sets: Lib/test/test_socket.py

Issue 16510: Using appropriate checks in tests
Left Patch Set: Created 7 years ago
Right Patch Set: Created 5 years, 10 months ago
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
Left: Side by side diff | Download
Right: Side by side diff | Download
« no previous file with change/comment | « Lib/test/test_slice.py ('k') | Lib/test/test_ssl.py » ('j') | no next file with change/comment »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
LEFTRIGHT
1 #!/usr/bin/env python3
2
3 import unittest 1 import unittest
4 from test import support 2 from test import support
5 from unittest.case import _ExpectedFailure
6 3
7 import errno 4 import errno
8 import io 5 import io
9 import socket 6 import socket
10 import select 7 import select
11 import tempfile 8 import tempfile
12 import _testcapi
13 import time 9 import time
14 import traceback 10 import traceback
15 import queue 11 import queue
16 import sys 12 import sys
17 import os 13 import os
18 import array 14 import array
19 import platform 15 import platform
20 import contextlib 16 import contextlib
21 from weakref import proxy 17 from weakref import proxy
22 import signal 18 import signal
23 import math 19 import math
24 import pickle 20 import pickle
25 import struct 21 import struct
26 try: 22 try:
27 import fcntl
28 except ImportError:
29 fcntl = False
30 try:
31 import multiprocessing 23 import multiprocessing
32 except ImportError: 24 except ImportError:
33 multiprocessing = False 25 multiprocessing = False
26 try:
27 import fcntl
28 except ImportError:
29 fcntl = None
34 30
35 HOST = support.HOST 31 HOST = support.HOST
36 MSG = 'Michael Gilfix was here\u1234\r\n'.encode('utf-8') ## test unicode string and carriage return 32 MSG = 'Michael Gilfix was here\u1234\r\n'.encode('utf-8') ## test unicode string and carriage return
37 33
38 try: 34 try:
39 import _thread as thread 35 import _thread as thread
40 import threading 36 import threading
41 except ImportError: 37 except ImportError:
42 thread = None 38 thread = None
43 threading = None 39 threading = None
44 40
45 def _have_socket_can(): 41 def _have_socket_can():
46 """Check whether CAN sockets are supported on this host.""" 42 """Check whether CAN sockets are supported on this host."""
47 try: 43 try:
48 s = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) 44 s = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
49 except (AttributeError, socket.error, OSError): 45 except (AttributeError, OSError):
50 return False 46 return False
51 else: 47 else:
52 s.close() 48 s.close()
53 return True 49 return True
54 50
55 def _have_socket_rds(): 51 def _have_socket_rds():
56 """Check whether RDS sockets are supported on this host.""" 52 """Check whether RDS sockets are supported on this host."""
57 try: 53 try:
58 s = socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0) 54 s = socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0)
59 except (AttributeError, OSError): 55 except (AttributeError, OSError):
(...skipping 54 matching lines...) Expand 10 before | Expand all | Expand 10 after
114 110
115 """To be able to run this test, a `vcan0` CAN interface can be created with 111 """To be able to run this test, a `vcan0` CAN interface can be created with
116 the following commands: 112 the following commands:
117 # modprobe vcan 113 # modprobe vcan
118 # ip link add dev vcan0 type vcan 114 # ip link add dev vcan0 type vcan
119 # ifconfig vcan0 up 115 # ifconfig vcan0 up
120 """ 116 """
121 interface = 'vcan0' 117 interface = 'vcan0'
122 bufsize = 128 118 bufsize = 128
123 119
120 """The CAN frame structure is defined in <linux/can.h>:
121
122 struct can_frame {
123 canid_t can_id; /* 32 bit CAN_ID + EFF/RTR/ERR flags */
124 __u8 can_dlc; /* data length code: 0 .. 8 */
125 __u8 data[8] __attribute__((aligned(8)));
126 };
127 """
128 can_frame_fmt = "=IB3x8s"
129 can_frame_size = struct.calcsize(can_frame_fmt)
130
131 """The Broadcast Management Command frame structure is defined
132 in <linux/can/bcm.h>:
133
134 struct bcm_msg_head {
135 __u32 opcode;
136 __u32 flags;
137 __u32 count;
138 struct timeval ival1, ival2;
139 canid_t can_id;
140 __u32 nframes;
141 struct can_frame frames[0];
142 }
143
144 `bcm_msg_head` must be 8 bytes aligned because of the `frames` member (see
145 `struct can_frame` definition). Must use native not standard types for packi ng.
146 """
147 bcm_cmd_msg_fmt = "@3I4l2I"
148 bcm_cmd_msg_fmt += "x" * (struct.calcsize(bcm_cmd_msg_fmt) % 8)
149
124 def setUp(self): 150 def setUp(self):
125 self.s = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) 151 self.s = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
126 self.addCleanup(self.s.close) 152 self.addCleanup(self.s.close)
127 try: 153 try:
128 self.s.bind((self.interface,)) 154 self.s.bind((self.interface,))
129 except socket.error: 155 except OSError:
130 self.skipTest('network interface `%s` does not exist' % 156 self.skipTest('network interface `%s` does not exist' %
131 self.interface) 157 self.interface)
132 158
133 159
134 class SocketRDSTest(unittest.TestCase): 160 class SocketRDSTest(unittest.TestCase):
135 161
136 """To be able to run this test, the `rds` kernel module must be loaded: 162 """To be able to run this test, the `rds` kernel module must be loaded:
137 # modprobe rds 163 # modprobe rds
138 """ 164 """
139 bufsize = 8192 165 bufsize = 8192
(...skipping 95 matching lines...) Expand 10 before | Expand all | Expand 10 after
235 self.server_ready.wait() 261 self.server_ready.wait()
236 self.clientSetUp() 262 self.clientSetUp()
237 self.client_ready.set() 263 self.client_ready.set()
238 if self.server_crashed: 264 if self.server_crashed:
239 self.clientTearDown() 265 self.clientTearDown()
240 return 266 return
241 if not hasattr(test_func, '__call__'): 267 if not hasattr(test_func, '__call__'):
242 raise TypeError("test_func must be a callable function") 268 raise TypeError("test_func must be a callable function")
243 try: 269 try:
244 test_func() 270 test_func()
245 except _ExpectedFailure:
246 # We deliberately ignore expected failures
247 pass
248 except BaseException as e: 271 except BaseException as e:
249 self.queue.put(e) 272 self.queue.put(e)
250 finally: 273 finally:
251 self.clientTearDown() 274 self.clientTearDown()
252 275
253 def clientSetUp(self): 276 def clientSetUp(self):
254 raise NotImplementedError("clientSetUp must be implemented.") 277 raise NotImplementedError("clientSetUp must be implemented.")
255 278
256 def clientTearDown(self): 279 def clientTearDown(self):
257 self.done.set() 280 self.done.set()
(...skipping 30 matching lines...) Expand all
288 class ThreadedCANSocketTest(SocketCANTest, ThreadableTest): 311 class ThreadedCANSocketTest(SocketCANTest, ThreadableTest):
289 312
290 def __init__(self, methodName='runTest'): 313 def __init__(self, methodName='runTest'):
291 SocketCANTest.__init__(self, methodName=methodName) 314 SocketCANTest.__init__(self, methodName=methodName)
292 ThreadableTest.__init__(self) 315 ThreadableTest.__init__(self)
293 316
294 def clientSetUp(self): 317 def clientSetUp(self):
295 self.cli = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) 318 self.cli = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
296 try: 319 try:
297 self.cli.bind((self.interface,)) 320 self.cli.bind((self.interface,))
298 except socket.error: 321 except OSError:
299 # skipTest should not be called here, and will be called in the 322 # skipTest should not be called here, and will be called in the
300 # server instead 323 # server instead
301 pass 324 pass
302 325
303 def clientTearDown(self): 326 def clientTearDown(self):
304 self.cli.close() 327 self.cli.close()
305 self.cli = None 328 self.cli = None
306 ThreadableTest.clientTearDown(self) 329 ThreadableTest.clientTearDown(self)
307 330
308 class ThreadedRDSSocketTest(SocketRDSTest, ThreadableTest): 331 class ThreadedRDSSocketTest(SocketRDSTest, ThreadableTest):
(...skipping 227 matching lines...) Expand 10 before | Expand all | Expand 10 after
536 """Base class for SCTP tests in one-to-one (SOCK_STREAM) mode.""" 559 """Base class for SCTP tests in one-to-one (SOCK_STREAM) mode."""
537 560
538 def newSocket(self): 561 def newSocket(self):
539 return socket.socket(socket.AF_INET, socket.SOCK_STREAM, 562 return socket.socket(socket.AF_INET, socket.SOCK_STREAM,
540 socket.IPPROTO_SCTP) 563 socket.IPPROTO_SCTP)
541 564
542 565
543 class Inet6TestBase(InetTestBase): 566 class Inet6TestBase(InetTestBase):
544 """Base class for IPv6 socket tests.""" 567 """Base class for IPv6 socket tests."""
545 568
546 # Don't use "localhost" here - it may not have an IPv6 address 569 host = support.HOSTv6
547 # assigned to it by default (e.g. in /etc/hosts), and if someone
548 # has assigned it an IPv4-mapped address, then it's unlikely to
549 # work with the full IPv6 API.
550 host = "::1"
551 570
552 class UDP6TestBase(Inet6TestBase): 571 class UDP6TestBase(Inet6TestBase):
553 """Base class for UDP-over-IPv6 tests.""" 572 """Base class for UDP-over-IPv6 tests."""
554 573
555 def newSocket(self): 574 def newSocket(self):
556 return socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) 575 return socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
557 576
558 577
559 # Test-skipping decorators for use with ThreadableTest. 578 # Test-skipping decorators for use with ThreadableTest.
560 579
(...skipping 40 matching lines...) Expand 10 before | Expand all | Expand 10 after
601 err = None 620 err = None
602 missing = [obj for obj in args if 621 missing = [obj for obj in args if
603 isinstance(obj, str) and not hasattr(socket, obj)] 622 isinstance(obj, str) and not hasattr(socket, obj)]
604 if missing: 623 if missing:
605 err = "don't have " + ", ".join(name for name in missing) 624 err = "don't have " + ", ".join(name for name in missing)
606 else: 625 else:
607 callargs = [getattr(socket, obj) if isinstance(obj, str) else obj 626 callargs = [getattr(socket, obj) if isinstance(obj, str) else obj
608 for obj in args] 627 for obj in args]
609 try: 628 try:
610 s = socket.socket(*callargs) 629 s = socket.socket(*callargs)
611 except socket.error as e: 630 except OSError as e:
612 # XXX: check errno? 631 # XXX: check errno?
613 err = str(e) 632 err = str(e)
614 else: 633 else:
615 s.close() 634 s.close()
616 return skipWithClientIf( 635 return skipWithClientIf(
617 err is not None, 636 err is not None,
618 "can't create socket({0}): {1}".format( 637 "can't create socket({0}): {1}".format(
619 ", ".join(str(o) for o in args), err)) 638 ", ".join(str(o) for o in args), err))
620 639
621 640
622 ####################################################################### 641 #######################################################################
623 ## Begin Tests 642 ## Begin Tests
624 643
625 class GeneralModuleTests(unittest.TestCase): 644 class GeneralModuleTests(unittest.TestCase):
626 645
627 def test_repr(self): 646 def test_repr(self):
628 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 647 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
629 self.addCleanup(s.close) 648 with s:
630 self.assertTrue(repr(s).startswith("<socket.socket object")) 649 self.assertIn('fd=%i' % s.fileno(), repr(s))
650 self.assertIn('family=%s' % socket.AF_INET, repr(s))
651 self.assertIn('type=%s' % socket.SOCK_STREAM, repr(s))
652 self.assertIn('proto=0', repr(s))
653 self.assertNotIn('raddr', repr(s))
654 s.bind(('127.0.0.1', 0))
655 self.assertIn('laddr', repr(s))
656 self.assertIn(str(s.getsockname()), repr(s))
657 self.assertIn('[closed]', repr(s))
658 self.assertNotIn('laddr', repr(s))
631 659
632 def test_weakref(self): 660 def test_weakref(self):
633 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 661 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
634 p = proxy(s) 662 p = proxy(s)
635 self.assertEqual(p.fileno(), s.fileno()) 663 self.assertEqual(p.fileno(), s.fileno())
636 s.close() 664 s.close()
637 s = None 665 s = None
638 try: 666 try:
639 p.fileno() 667 p.fileno()
640 except ReferenceError: 668 except ReferenceError:
641 pass 669 pass
642 else: 670 else:
643 self.fail('Socket proxy still exists') 671 self.fail('Socket proxy still exists')
644 672
645 def testSocketError(self): 673 def testSocketError(self):
646 # Testing socket module exceptions 674 # Testing socket module exceptions
647 msg = "Error raising socket exception (%s)." 675 msg = "Error raising socket exception (%s)."
648 with self.assertRaises(socket.error, msg=msg % 'socket.error'): 676 with self.assertRaises(OSError, msg=msg % 'OSError'):
649 raise socket.error 677 raise OSError
650 with self.assertRaises(socket.error, msg=msg % 'socket.herror'): 678 with self.assertRaises(OSError, msg=msg % 'socket.herror'):
651 raise socket.herror 679 raise socket.herror
652 with self.assertRaises(socket.error, msg=msg % 'socket.gaierror'): 680 with self.assertRaises(OSError, msg=msg % 'socket.gaierror'):
653 raise socket.gaierror 681 raise socket.gaierror
654 682
655 def testSendtoErrors(self): 683 def testSendtoErrors(self):
656 # Testing that sendto doens't masks failures. See #10169. 684 # Testing that sendto doens't masks failures. See #10169.
657 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 685 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
658 self.addCleanup(s.close) 686 self.addCleanup(s.close)
659 s.bind(('', 0)) 687 s.bind(('', 0))
660 sockname = s.getsockname() 688 sockname = s.getsockname()
661 # 2 args 689 # 2 args
662 with self.assertRaises(TypeError) as cm: 690 with self.assertRaises(TypeError) as cm:
(...skipping 42 matching lines...) Expand 10 before | Expand all | Expand 10 after
705 socket.SOCK_RDM 733 socket.SOCK_RDM
706 socket.SOCK_SEQPACKET 734 socket.SOCK_SEQPACKET
707 socket.SOL_SOCKET 735 socket.SOL_SOCKET
708 socket.SO_REUSEADDR 736 socket.SO_REUSEADDR
709 737
710 def testHostnameRes(self): 738 def testHostnameRes(self):
711 # Testing hostname resolution mechanisms 739 # Testing hostname resolution mechanisms
712 hostname = socket.gethostname() 740 hostname = socket.gethostname()
713 try: 741 try:
714 ip = socket.gethostbyname(hostname) 742 ip = socket.gethostbyname(hostname)
715 except socket.error: 743 except OSError:
716 # Probably name lookup wasn't set up right; skip this test 744 # Probably name lookup wasn't set up right; skip this test
717 return 745 self.skipTest('name lookup failure')
718 self.assertGreaterEqual(ip.find('.'), 0, "Error resolving host to ip.") 746 self.assertIn('.', ip, "Error resolving host to ip.")
719 try: 747 try:
720 hname, aliases, ipaddrs = socket.gethostbyaddr(ip) 748 hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
721 except socket.error: 749 except OSError:
722 # Probably a similar problem as above; skip this test 750 # Probably a similar problem as above; skip this test
723 return 751 self.skipTest('name lookup failure')
724 all_host_names = [hostname, hname] + aliases 752 all_host_names = [hostname, hname] + aliases
725 fqhn = socket.getfqdn(ip) 753 fqhn = socket.getfqdn(ip)
726 if not fqhn in all_host_names: 754 if not fqhn in all_host_names:
727 self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names))) 755 self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names)))
756
757 def test_host_resolution(self):
758 for addr in ['0.1.1.~1', '1+.1.1.1', '::1q', '::1::2',
759 '1:1:1:1:1:1:1:1:1']:
760 self.assertRaises(OSError, socket.gethostbyname, addr)
761 self.assertRaises(OSError, socket.gethostbyaddr, addr)
762
763 for addr in [support.HOST, '10.0.0.1', '255.255.255.255']:
764 self.assertEqual(socket.gethostbyname(addr), addr)
765
766 # we don't test support.HOSTv6 because there's a chance it doesn't have
767 # a matching name entry (e.g. 'ip6-localhost')
768 for host in [support.HOST]:
769 self.assertIn(host, socket.gethostbyaddr(host)[2])
728 770
729 @unittest.skipUnless(hasattr(socket, 'sethostname'), "test needs socket.seth ostname()") 771 @unittest.skipUnless(hasattr(socket, 'sethostname'), "test needs socket.seth ostname()")
730 @unittest.skipUnless(hasattr(socket, 'gethostname'), "test needs socket.geth ostname()") 772 @unittest.skipUnless(hasattr(socket, 'gethostname'), "test needs socket.geth ostname()")
731 def test_sethostname(self): 773 def test_sethostname(self):
732 oldhn = socket.gethostname() 774 oldhn = socket.gethostname()
733 try: 775 try:
734 socket.sethostname('new') 776 socket.sethostname('new')
735 except socket.error as e: 777 except OSError as e:
736 if e.errno == errno.EPERM: 778 if e.errno == errno.EPERM:
737 self.skipTest("test should be run as root") 779 self.skipTest("test should be run as root")
738 else: 780 else:
739 raise 781 raise
740 try: 782 try:
741 # running test as root! 783 # running test as root!
742 self.assertEqual(socket.gethostname(), 'new') 784 self.assertEqual(socket.gethostname(), 'new')
743 # Should work with bytes objects too 785 # Should work with bytes objects too
744 socket.sethostname(b'bar') 786 socket.sethostname(b'bar')
745 self.assertEqual(socket.gethostname(), 'bar') 787 self.assertEqual(socket.gethostname(), 'bar')
(...skipping 13 matching lines...) Expand all
759 self.assertIsInstance(_index, int) 801 self.assertIsInstance(_index, int)
760 self.assertEqual(index, _index) 802 self.assertEqual(index, _index)
761 _name = socket.if_indextoname(index) 803 _name = socket.if_indextoname(index)
762 self.assertIsInstance(_name, str) 804 self.assertIsInstance(_name, str)
763 self.assertEqual(name, _name) 805 self.assertEqual(name, _name)
764 806
765 @unittest.skipUnless(hasattr(socket, 'if_nameindex'), 807 @unittest.skipUnless(hasattr(socket, 'if_nameindex'),
766 'socket.if_nameindex() not available.') 808 'socket.if_nameindex() not available.')
767 def testInvalidInterfaceNameIndex(self): 809 def testInvalidInterfaceNameIndex(self):
768 # test nonexistent interface index/name 810 # test nonexistent interface index/name
769 self.assertRaises(socket.error, socket.if_indextoname, 0) 811 self.assertRaises(OSError, socket.if_indextoname, 0)
770 self.assertRaises(socket.error, socket.if_nametoindex, '_DEADBEEF') 812 self.assertRaises(OSError, socket.if_nametoindex, '_DEADBEEF')
771 # test with invalid values 813 # test with invalid values
772 self.assertRaises(TypeError, socket.if_nametoindex, 0) 814 self.assertRaises(TypeError, socket.if_nametoindex, 0)
773 self.assertRaises(TypeError, socket.if_indextoname, '_DEADBEEF') 815 self.assertRaises(TypeError, socket.if_indextoname, '_DEADBEEF')
774 816
817 @unittest.skipUnless(hasattr(sys, 'getrefcount'),
818 'test needs sys.getrefcount()')
775 def testRefCountGetNameInfo(self): 819 def testRefCountGetNameInfo(self):
776 # Testing reference count for getnameinfo 820 # Testing reference count for getnameinfo
777 if hasattr(sys, "getrefcount"): 821 try:
778 try: 822 # On some versions, this loses a reference
779 # On some versions, this loses a reference 823 orig = sys.getrefcount(__name__)
780 orig = sys.getrefcount(__name__) 824 socket.getnameinfo(__name__,0)
781 socket.getnameinfo(__name__,0) 825 except TypeError:
782 except TypeError: 826 if sys.getrefcount(__name__) != orig:
783 if sys.getrefcount(__name__) != orig: 827 self.fail("socket.getnameinfo loses a reference")
784 self.fail("socket.getnameinfo loses a reference")
785 828
786 def testInterpreterCrash(self): 829 def testInterpreterCrash(self):
787 # Making sure getnameinfo doesn't crash the interpreter 830 # Making sure getnameinfo doesn't crash the interpreter
788 try: 831 try:
789 # On some versions, this crashes the interpreter. 832 # On some versions, this crashes the interpreter.
790 socket.getnameinfo(('x', 0, 0, 0), 0) 833 socket.getnameinfo(('x', 0, 0, 0), 0)
791 except socket.error: 834 except OSError:
792 pass 835 pass
793 836
794 def testNtoH(self): 837 def testNtoH(self):
795 # This just checks that htons etc. are their own inverse, 838 # This just checks that htons etc. are their own inverse,
796 # when looking at the lower 16 or 32 bits. 839 # when looking at the lower 16 or 32 bits.
797 sizes = {socket.htonl: 32, socket.ntohl: 32, 840 sizes = {socket.htonl: 32, socket.ntohl: 32,
798 socket.htons: 16, socket.ntohs: 16} 841 socket.htons: 16, socket.ntohs: 16}
799 for func, size in sizes.items(): 842 for func, size in sizes.items():
800 mask = (1<<size) - 1 843 mask = (1<<size) - 1
801 for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210): 844 for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210):
(...skipping 26 matching lines...) Expand all
828 or sys.platform in ('linux', 'darwin')): 871 or sys.platform in ('linux', 'darwin')):
829 # avoid the 'echo' service on this platform, as there is an 872 # avoid the 'echo' service on this platform, as there is an
830 # assumption breaking non-standard port/protocol entry 873 # assumption breaking non-standard port/protocol entry
831 services = ('daytime', 'qotd', 'domain') 874 services = ('daytime', 'qotd', 'domain')
832 else: 875 else:
833 services = ('echo', 'daytime', 'domain') 876 services = ('echo', 'daytime', 'domain')
834 for service in services: 877 for service in services:
835 try: 878 try:
836 port = socket.getservbyname(service, 'tcp') 879 port = socket.getservbyname(service, 'tcp')
837 break 880 break
838 except socket.error: 881 except OSError:
839 pass 882 pass
840 else: 883 else:
841 raise socket.error 884 raise OSError
842 # Try same call with optional protocol omitted 885 # Try same call with optional protocol omitted
843 port2 = socket.getservbyname(service) 886 port2 = socket.getservbyname(service)
844 eq(port, port2) 887 eq(port, port2)
845 # Try udp, but don't barf it it doesn't exist 888 # Try udp, but don't barf if it doesn't exist
846 try: 889 try:
847 udpport = socket.getservbyname(service, 'udp') 890 udpport = socket.getservbyname(service, 'udp')
848 except socket.error: 891 except OSError:
849 udpport = None 892 udpport = None
850 else: 893 else:
851 eq(udpport, port) 894 eq(udpport, port)
852 # Now make sure the lookup by port returns the same service name 895 # Now make sure the lookup by port returns the same service name
853 eq(socket.getservbyport(port2), service) 896 eq(socket.getservbyport(port2), service)
854 eq(socket.getservbyport(port, 'tcp'), service) 897 eq(socket.getservbyport(port, 'tcp'), service)
855 if udpport is not None: 898 if udpport is not None:
856 eq(socket.getservbyport(udpport, 'udp'), service) 899 eq(socket.getservbyport(udpport, 'udp'), service)
857 # Make sure getservbyport does not accept out of range ports. 900 # Make sure getservbyport does not accept out of range ports.
858 self.assertRaises(OverflowError, socket.getservbyport, -1) 901 self.assertRaises(OverflowError, socket.getservbyport, -1)
(...skipping 20 matching lines...) Expand all
879 s = socket.socket() 922 s = socket.socket()
880 self.assertEqual(s.gettimeout(), None) 923 self.assertEqual(s.gettimeout(), None)
881 s.close() 924 s.close()
882 925
883 # Check that setting it to an invalid value raises ValueError 926 # Check that setting it to an invalid value raises ValueError
884 self.assertRaises(ValueError, socket.setdefaulttimeout, -1) 927 self.assertRaises(ValueError, socket.setdefaulttimeout, -1)
885 928
886 # Check that setting it to an invalid type raises TypeError 929 # Check that setting it to an invalid type raises TypeError
887 self.assertRaises(TypeError, socket.setdefaulttimeout, "spam") 930 self.assertRaises(TypeError, socket.setdefaulttimeout, "spam")
888 931
932 @unittest.skipUnless(hasattr(socket, 'inet_aton'),
933 'test needs socket.inet_aton()')
889 def testIPv4_inet_aton_fourbytes(self): 934 def testIPv4_inet_aton_fourbytes(self):
890 if not hasattr(socket, 'inet_aton'):
891 return # No inet_aton, nothing to check
892 # Test that issue1008086 and issue767150 are fixed. 935 # Test that issue1008086 and issue767150 are fixed.
893 # It must return 4 bytes. 936 # It must return 4 bytes.
894 self.assertEqual(b'\x00'*4, socket.inet_aton('0.0.0.0')) 937 self.assertEqual(b'\x00'*4, socket.inet_aton('0.0.0.0'))
895 self.assertEqual(b'\xff'*4, socket.inet_aton('255.255.255.255')) 938 self.assertEqual(b'\xff'*4, socket.inet_aton('255.255.255.255'))
896 939
940 @unittest.skipUnless(hasattr(socket, 'inet_pton'),
941 'test needs socket.inet_pton()')
897 def testIPv4toString(self): 942 def testIPv4toString(self):
898 if not hasattr(socket, 'inet_pton'):
899 return # No inet_pton() on this platform
900 from socket import inet_aton as f, inet_pton, AF_INET 943 from socket import inet_aton as f, inet_pton, AF_INET
901 g = lambda a: inet_pton(AF_INET, a) 944 g = lambda a: inet_pton(AF_INET, a)
902 945
903 assertInvalid = lambda func,a: self.assertRaises( 946 assertInvalid = lambda func,a: self.assertRaises(
904 (socket.error, ValueError), func, a 947 (OSError, ValueError), func, a
905 ) 948 )
906 949
907 self.assertEqual(b'\x00\x00\x00\x00', f('0.0.0.0')) 950 self.assertEqual(b'\x00\x00\x00\x00', f('0.0.0.0'))
908 self.assertEqual(b'\xff\x00\xff\x00', f('255.0.255.0')) 951 self.assertEqual(b'\xff\x00\xff\x00', f('255.0.255.0'))
909 self.assertEqual(b'\xaa\xaa\xaa\xaa', f('170.170.170.170')) 952 self.assertEqual(b'\xaa\xaa\xaa\xaa', f('170.170.170.170'))
910 self.assertEqual(b'\x01\x02\x03\x04', f('1.2.3.4')) 953 self.assertEqual(b'\x01\x02\x03\x04', f('1.2.3.4'))
911 self.assertEqual(b'\xff\xff\xff\xff', f('255.255.255.255')) 954 self.assertEqual(b'\xff\xff\xff\xff', f('255.255.255.255'))
912 assertInvalid(f, '0.0.0.') 955 assertInvalid(f, '0.0.0.')
913 assertInvalid(f, '300.0.0.0') 956 assertInvalid(f, '300.0.0.0')
914 assertInvalid(f, 'a.0.0.0') 957 assertInvalid(f, 'a.0.0.0')
915 assertInvalid(f, '1.2.3.4.5') 958 assertInvalid(f, '1.2.3.4.5')
916 assertInvalid(f, '::1') 959 assertInvalid(f, '::1')
917 960
918 self.assertEqual(b'\x00\x00\x00\x00', g('0.0.0.0')) 961 self.assertEqual(b'\x00\x00\x00\x00', g('0.0.0.0'))
919 self.assertEqual(b'\xff\x00\xff\x00', g('255.0.255.0')) 962 self.assertEqual(b'\xff\x00\xff\x00', g('255.0.255.0'))
920 self.assertEqual(b'\xaa\xaa\xaa\xaa', g('170.170.170.170')) 963 self.assertEqual(b'\xaa\xaa\xaa\xaa', g('170.170.170.170'))
921 self.assertEqual(b'\xff\xff\xff\xff', g('255.255.255.255')) 964 self.assertEqual(b'\xff\xff\xff\xff', g('255.255.255.255'))
922 assertInvalid(g, '0.0.0.') 965 assertInvalid(g, '0.0.0.')
923 assertInvalid(g, '300.0.0.0') 966 assertInvalid(g, '300.0.0.0')
924 assertInvalid(g, 'a.0.0.0') 967 assertInvalid(g, 'a.0.0.0')
925 assertInvalid(g, '1.2.3.4.5') 968 assertInvalid(g, '1.2.3.4.5')
926 assertInvalid(g, '::1') 969 assertInvalid(g, '::1')
927 970
971 @unittest.skipUnless(hasattr(socket, 'inet_pton'),
972 'test needs socket.inet_pton()')
928 def testIPv6toString(self): 973 def testIPv6toString(self):
929 if not hasattr(socket, 'inet_pton'):
930 return # No inet_pton() on this platform
931 try: 974 try:
932 from socket import inet_pton, AF_INET6, has_ipv6 975 from socket import inet_pton, AF_INET6, has_ipv6
933 if not has_ipv6: 976 if not has_ipv6:
934 return 977 self.skipTest('IPv6 not available')
935 except ImportError: 978 except ImportError:
936 return 979 self.skipTest('could not import needed symbols from socket')
980
981 if sys.platform == "win32":
982 try:
983 inet_pton(AF_INET6, '::')
984 except OSError as e:
985 if e.winerror == 10022:
986 self.skipTest('IPv6 might not be supported')
987
937 f = lambda a: inet_pton(AF_INET6, a) 988 f = lambda a: inet_pton(AF_INET6, a)
938 assertInvalid = lambda a: self.assertRaises( 989 assertInvalid = lambda a: self.assertRaises(
939 (socket.error, ValueError), f, a 990 (OSError, ValueError), f, a
940 ) 991 )
941 992
942 self.assertEqual(b'\x00' * 16, f('::')) 993 self.assertEqual(b'\x00' * 16, f('::'))
943 self.assertEqual(b'\x00' * 16, f('0::0')) 994 self.assertEqual(b'\x00' * 16, f('0::0'))
944 self.assertEqual(b'\x00\x01' + b'\x00' * 14, f('1::')) 995 self.assertEqual(b'\x00\x01' + b'\x00' * 14, f('1::'))
945 self.assertEqual( 996 self.assertEqual(
946 b'\x45\xef\x76\xcb\x00\x1a\x56\xef\xaf\xeb\x0b\xac\x19\x24\xae\xae', 997 b'\x45\xef\x76\xcb\x00\x1a\x56\xef\xaf\xeb\x0b\xac\x19\x24\xae\xae',
947 f('45ef:76cb:1a:56ef:afeb:bac:1924:aeae') 998 f('45ef:76cb:1a:56ef:afeb:bac:1924:aeae')
948 ) 999 )
949 self.assertEqual( 1000 self.assertEqual(
(...skipping 22 matching lines...) Expand all
972 b'\x00\x42\xa8\xb9\x00\x00\x00\x02\xff\xff\xa2\x9b\xfe\x2a\x17\x40', 1023 b'\x00\x42\xa8\xb9\x00\x00\x00\x02\xff\xff\xa2\x9b\xfe\x2a\x17\x40',
973 f('42:a8b9:0:2:ffff:a29b:254.42.23.64') 1024 f('42:a8b9:0:2:ffff:a29b:254.42.23.64')
974 ) 1025 )
975 assertInvalid('255.254.253.252') 1026 assertInvalid('255.254.253.252')
976 assertInvalid('1::260.2.3.0') 1027 assertInvalid('1::260.2.3.0')
977 assertInvalid('1::0.be.e.0') 1028 assertInvalid('1::0.be.e.0')
978 assertInvalid('1:2:3:4:5:6:7:1.2.3.4') 1029 assertInvalid('1:2:3:4:5:6:7:1.2.3.4')
979 assertInvalid('::1.2.3.4:0') 1030 assertInvalid('::1.2.3.4:0')
980 assertInvalid('0.100.200.0:3:4:5:6:7:8') 1031 assertInvalid('0.100.200.0:3:4:5:6:7:8')
981 1032
1033 @unittest.skipUnless(hasattr(socket, 'inet_ntop'),
1034 'test needs socket.inet_ntop()')
982 def testStringToIPv4(self): 1035 def testStringToIPv4(self):
983 if not hasattr(socket, 'inet_ntop'):
984 return # No inet_ntop() on this platform
985 from socket import inet_ntoa as f, inet_ntop, AF_INET 1036 from socket import inet_ntoa as f, inet_ntop, AF_INET
986 g = lambda a: inet_ntop(AF_INET, a) 1037 g = lambda a: inet_ntop(AF_INET, a)
987 assertInvalid = lambda func,a: self.assertRaises( 1038 assertInvalid = lambda func,a: self.assertRaises(
988 (socket.error, ValueError), func, a 1039 (OSError, ValueError), func, a
989 ) 1040 )
990 1041
991 self.assertEqual('1.0.1.0', f(b'\x01\x00\x01\x00')) 1042 self.assertEqual('1.0.1.0', f(b'\x01\x00\x01\x00'))
992 self.assertEqual('170.85.170.85', f(b'\xaa\x55\xaa\x55')) 1043 self.assertEqual('170.85.170.85', f(b'\xaa\x55\xaa\x55'))
993 self.assertEqual('255.255.255.255', f(b'\xff\xff\xff\xff')) 1044 self.assertEqual('255.255.255.255', f(b'\xff\xff\xff\xff'))
994 self.assertEqual('1.2.3.4', f(b'\x01\x02\x03\x04')) 1045 self.assertEqual('1.2.3.4', f(b'\x01\x02\x03\x04'))
995 assertInvalid(f, b'\x00' * 3) 1046 assertInvalid(f, b'\x00' * 3)
996 assertInvalid(f, b'\x00' * 5) 1047 assertInvalid(f, b'\x00' * 5)
997 assertInvalid(f, b'\x00' * 16) 1048 assertInvalid(f, b'\x00' * 16)
998 1049
999 self.assertEqual('1.0.1.0', g(b'\x01\x00\x01\x00')) 1050 self.assertEqual('1.0.1.0', g(b'\x01\x00\x01\x00'))
1000 self.assertEqual('170.85.170.85', g(b'\xaa\x55\xaa\x55')) 1051 self.assertEqual('170.85.170.85', g(b'\xaa\x55\xaa\x55'))
1001 self.assertEqual('255.255.255.255', g(b'\xff\xff\xff\xff')) 1052 self.assertEqual('255.255.255.255', g(b'\xff\xff\xff\xff'))
1002 assertInvalid(g, b'\x00' * 3) 1053 assertInvalid(g, b'\x00' * 3)
1003 assertInvalid(g, b'\x00' * 5) 1054 assertInvalid(g, b'\x00' * 5)
1004 assertInvalid(g, b'\x00' * 16) 1055 assertInvalid(g, b'\x00' * 16)
1005 1056
1057 @unittest.skipUnless(hasattr(socket, 'inet_ntop'),
1058 'test needs socket.inet_ntop()')
1006 def testStringToIPv6(self): 1059 def testStringToIPv6(self):
1007 if not hasattr(socket, 'inet_ntop'):
1008 return # No inet_ntop() on this platform
1009 try: 1060 try:
1010 from socket import inet_ntop, AF_INET6, has_ipv6 1061 from socket import inet_ntop, AF_INET6, has_ipv6
1011 if not has_ipv6: 1062 if not has_ipv6:
1012 return 1063 self.skipTest('IPv6 not available')
1013 except ImportError: 1064 except ImportError:
1014 return 1065 self.skipTest('could not import needed symbols from socket')
1066
1067 if sys.platform == "win32":
1068 try:
1069 inet_ntop(AF_INET6, b'\x00' * 16)
1070 except OSError as e:
1071 if e.winerror == 10022:
1072 self.skipTest('IPv6 might not be supported')
1073
1015 f = lambda a: inet_ntop(AF_INET6, a) 1074 f = lambda a: inet_ntop(AF_INET6, a)
1016 assertInvalid = lambda a: self.assertRaises( 1075 assertInvalid = lambda a: self.assertRaises(
1017 (socket.error, ValueError), f, a 1076 (OSError, ValueError), f, a
1018 ) 1077 )
1019 1078
1020 self.assertEqual('::', f(b'\x00' * 16)) 1079 self.assertEqual('::', f(b'\x00' * 16))
1021 self.assertEqual('::1', f(b'\x00' * 15 + b'\x01')) 1080 self.assertEqual('::1', f(b'\x00' * 15 + b'\x01'))
1022 self.assertEqual( 1081 self.assertEqual(
1023 'aef:b01:506:1001:ffff:9997:55:170', 1082 'aef:b01:506:1001:ffff:9997:55:170',
1024 f(b'\x0a\xef\x0b\x01\x05\x06\x10\x01\xff\xff\x99\x97\x00\x55\x01\x70 ') 1083 f(b'\x0a\xef\x0b\x01\x05\x06\x10\x01\xff\xff\x99\x97\x00\x55\x01\x70 ')
1025 ) 1084 )
1026 1085
1027 assertInvalid(b'\x12' * 15) 1086 assertInvalid(b'\x12' * 15)
1028 assertInvalid(b'\x12' * 17) 1087 assertInvalid(b'\x12' * 17)
1029 assertInvalid(b'\x12' * 4) 1088 assertInvalid(b'\x12' * 4)
1030 1089
1031 # XXX The following don't test module-level functionality... 1090 # XXX The following don't test module-level functionality...
1032 1091
1033 def testSockName(self): 1092 def testSockName(self):
1034 # Testing getsockname() 1093 # Testing getsockname()
1035 port = support.find_unused_port() 1094 port = support.find_unused_port()
1036 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 1095 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1037 self.addCleanup(sock.close) 1096 self.addCleanup(sock.close)
1038 sock.bind(("0.0.0.0", port)) 1097 sock.bind(("0.0.0.0", port))
1039 name = sock.getsockname() 1098 name = sock.getsockname()
1040 # XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate 1099 # XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate
1041 # it reasonable to get the host's addr in addition to 0.0.0.0. 1100 # it reasonable to get the host's addr in addition to 0.0.0.0.
1042 # At least for eCos. This is required for the S/390 to pass. 1101 # At least for eCos. This is required for the S/390 to pass.
1043 try: 1102 try:
1044 my_ip_addr = socket.gethostbyname(socket.gethostname()) 1103 my_ip_addr = socket.gethostbyname(socket.gethostname())
1045 except socket.error: 1104 except OSError:
1046 # Probably name lookup wasn't set up right; skip this test 1105 # Probably name lookup wasn't set up right; skip this test
1047 return 1106 self.skipTest('name lookup failure')
1048 self.assertIn(name[0], ("0.0.0.0", my_ip_addr), '%s invalid' % name[0]) 1107 self.assertIn(name[0], ("0.0.0.0", my_ip_addr), '%s invalid' % name[0])
1049 self.assertEqual(name[1], port) 1108 self.assertEqual(name[1], port)
1050 1109
1051 def testGetSockOpt(self): 1110 def testGetSockOpt(self):
1052 # Testing getsockopt() 1111 # Testing getsockopt()
1053 # We know a socket should start without reuse==0 1112 # We know a socket should start without reuse==0
1054 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 1113 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1055 self.addCleanup(sock.close) 1114 self.addCleanup(sock.close)
1056 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) 1115 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
1057 self.assertEqual(reuse, 0, "initial mode is reuse") 1116 self.assertEqual(reuse, 0, "initial mode is reuse")
1058 1117
1059 def testSetSockOpt(self): 1118 def testSetSockOpt(self):
1060 # Testing setsockopt() 1119 # Testing setsockopt()
1061 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 1120 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1062 self.addCleanup(sock.close) 1121 self.addCleanup(sock.close)
1063 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 1122 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1064 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) 1123 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
1065 self.assertNotEqual(reuse, 0, "failed to set reuse mode") 1124 self.assertNotEqual(reuse, 0, "failed to set reuse mode")
1066 1125
1067 def testSendAfterClose(self): 1126 def testSendAfterClose(self):
1068 # testing send() after close() with timeout 1127 # testing send() after close() with timeout
1069 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 1128 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1070 sock.settimeout(1) 1129 sock.settimeout(1)
1071 sock.close() 1130 sock.close()
1072 self.assertRaises(socket.error, sock.send, b"spam") 1131 self.assertRaises(OSError, sock.send, b"spam")
1073 1132
1074 def testNewAttributes(self): 1133 def testNewAttributes(self):
1075 # testing .family, .type and .protocol 1134 # testing .family, .type and .protocol
1135
1076 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 1136 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1077 self.assertEqual(sock.family, socket.AF_INET) 1137 self.assertEqual(sock.family, socket.AF_INET)
1078 self.assertEqual(sock.type, socket.SOCK_STREAM) 1138 if hasattr(socket, 'SOCK_CLOEXEC'):
1139 self.assertIn(sock.type,
1140 (socket.SOCK_STREAM | socket.SOCK_CLOEXEC,
1141 socket.SOCK_STREAM))
1142 else:
1143 self.assertEqual(sock.type, socket.SOCK_STREAM)
1079 self.assertEqual(sock.proto, 0) 1144 self.assertEqual(sock.proto, 0)
1080 sock.close() 1145 sock.close()
1081 1146
1082 def test_getsockaddrarg(self): 1147 def test_getsockaddrarg(self):
1083 host = '0.0.0.0' 1148 host = '0.0.0.0'
1084 port = support.find_unused_port() 1149 port = support.find_unused_port()
1085 big_port = port + 65536 1150 big_port = port + 65536
1086 neg_port = port - 65536 1151 neg_port = port - 65536
1087 sock = socket.socket() 1152 sock = socket.socket()
1088 try: 1153 try:
(...skipping 32 matching lines...) Expand 10 before | Expand all | Expand 10 after
1121 socket.getaddrinfo('127.0.0.1', 80) 1186 socket.getaddrinfo('127.0.0.1', 80)
1122 socket.getaddrinfo(None, 80) 1187 socket.getaddrinfo(None, 80)
1123 if support.IPV6_ENABLED: 1188 if support.IPV6_ENABLED:
1124 socket.getaddrinfo('::1', 80) 1189 socket.getaddrinfo('::1', 80)
1125 # port can be a string service name such as "http", a numeric 1190 # port can be a string service name such as "http", a numeric
1126 # port number or None 1191 # port number or None
1127 socket.getaddrinfo(HOST, "http") 1192 socket.getaddrinfo(HOST, "http")
1128 socket.getaddrinfo(HOST, 80) 1193 socket.getaddrinfo(HOST, 80)
1129 socket.getaddrinfo(HOST, None) 1194 socket.getaddrinfo(HOST, None)
1130 # test family and socktype filters 1195 # test family and socktype filters
1131 infos = socket.getaddrinfo(HOST, None, socket.AF_INET) 1196 infos = socket.getaddrinfo(HOST, 80, socket.AF_INET, socket.SOCK_STREAM)
1132 for family, _, _, _, _ in infos: 1197 for family, type, _, _, _ in infos:
1133 self.assertEqual(family, socket.AF_INET) 1198 self.assertEqual(family, socket.AF_INET)
1199 self.assertEqual(str(family), 'AddressFamily.AF_INET')
1200 self.assertEqual(type, socket.SOCK_STREAM)
1201 self.assertEqual(str(type), 'SocketType.SOCK_STREAM')
1134 infos = socket.getaddrinfo(HOST, None, 0, socket.SOCK_STREAM) 1202 infos = socket.getaddrinfo(HOST, None, 0, socket.SOCK_STREAM)
1135 for _, socktype, _, _, _ in infos: 1203 for _, socktype, _, _, _ in infos:
1136 self.assertEqual(socktype, socket.SOCK_STREAM) 1204 self.assertEqual(socktype, socket.SOCK_STREAM)
1137 # test proto and flags arguments 1205 # test proto and flags arguments
1138 socket.getaddrinfo(HOST, None, 0, 0, socket.SOL_TCP) 1206 socket.getaddrinfo(HOST, None, 0, 0, socket.SOL_TCP)
1139 socket.getaddrinfo(HOST, None, 0, 0, 0, socket.AI_PASSIVE) 1207 socket.getaddrinfo(HOST, None, 0, 0, 0, socket.AI_PASSIVE)
1140 # a server willing to support both IPv4 and IPv6 will 1208 # a server willing to support both IPv4 and IPv6 will
1141 # usually do this 1209 # usually do this
1142 socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, 1210 socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
1143 socket.AI_PASSIVE) 1211 socket.AI_PASSIVE)
(...skipping 15 matching lines...) Expand all
1159 self.assertEqual(a, b) 1227 self.assertEqual(a, b)
1160 a = socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, 1228 a = socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
1161 socket.AI_PASSIVE) 1229 socket.AI_PASSIVE)
1162 b = socket.getaddrinfo(host=None, port=0, family=socket.AF_UNSPEC, 1230 b = socket.getaddrinfo(host=None, port=0, family=socket.AF_UNSPEC,
1163 type=socket.SOCK_STREAM, proto=0, 1231 type=socket.SOCK_STREAM, proto=0,
1164 flags=socket.AI_PASSIVE) 1232 flags=socket.AI_PASSIVE)
1165 self.assertEqual(a, b) 1233 self.assertEqual(a, b)
1166 # Issue #6697. 1234 # Issue #6697.
1167 self.assertRaises(UnicodeEncodeError, socket.getaddrinfo, 'localhost', ' \uD800') 1235 self.assertRaises(UnicodeEncodeError, socket.getaddrinfo, 'localhost', ' \uD800')
1168 1236
1237 # Issue 17269
1238 if hasattr(socket, 'AI_NUMERICSERV'):
1239 socket.getaddrinfo("localhost", None, 0, 0, 0, socket.AI_NUMERICSERV )
1240
1169 def test_getnameinfo(self): 1241 def test_getnameinfo(self):
1170 # only IP addresses are allowed 1242 # only IP addresses are allowed
1171 self.assertRaises(socket.error, socket.getnameinfo, ('mail.python.org',0 ), 0) 1243 self.assertRaises(OSError, socket.getnameinfo, ('mail.python.org',0), 0)
1172 1244
1173 @unittest.skipUnless(support.is_resource_enabled('network'), 1245 @unittest.skipUnless(support.is_resource_enabled('network'),
1174 'network is not enabled') 1246 'network is not enabled')
1175 def test_idna(self): 1247 def test_idna(self):
1176 # Check for internet access before running test (issue #12804). 1248 # Check for internet access before running test (issue #12804).
1177 try: 1249 try:
1178 socket.gethostbyname('python.org') 1250 socket.gethostbyname('python.org')
1179 except socket.gaierror as e: 1251 except socket.gaierror as e:
1180 if e.errno == socket.EAI_NODATA: 1252 if e.errno == socket.EAI_NODATA:
1181 self.skipTest('internet access required for this test') 1253 self.skipTest('internet access required for this test')
(...skipping 17 matching lines...) Expand all
1199 self.assertRaises(ValueError, math.acosh, 0) 1271 self.assertRaises(ValueError, math.acosh, 0)
1200 1 // 0 1272 1 // 0
1201 c, s = socket.socketpair() 1273 c, s = socket.socketpair()
1202 old_alarm = signal.signal(signal.SIGALRM, raising_handler) 1274 old_alarm = signal.signal(signal.SIGALRM, raising_handler)
1203 try: 1275 try:
1204 if with_timeout: 1276 if with_timeout:
1205 # Just above the one second minimum for signal.alarm 1277 # Just above the one second minimum for signal.alarm
1206 c.settimeout(1.5) 1278 c.settimeout(1.5)
1207 with self.assertRaises(ZeroDivisionError): 1279 with self.assertRaises(ZeroDivisionError):
1208 signal.alarm(1) 1280 signal.alarm(1)
1209 c.sendall(b"x" * (1024**2)) 1281 c.sendall(b"x" * support.SOCK_MAX_SIZE)
1210 if with_timeout: 1282 if with_timeout:
1211 signal.signal(signal.SIGALRM, ok_handler) 1283 signal.signal(signal.SIGALRM, ok_handler)
1212 signal.alarm(1) 1284 signal.alarm(1)
1213 self.assertRaises(socket.timeout, c.sendall, b"x" * (1024**2)) 1285 self.assertRaises(socket.timeout, c.sendall,
1286 b"x" * support.SOCK_MAX_SIZE)
1214 finally: 1287 finally:
1288 signal.alarm(0)
1215 signal.signal(signal.SIGALRM, old_alarm) 1289 signal.signal(signal.SIGALRM, old_alarm)
1216 c.close() 1290 c.close()
1217 s.close() 1291 s.close()
1218 1292
1219 def test_sendall_interrupted(self): 1293 def test_sendall_interrupted(self):
1220 self.check_sendall_interrupted(False) 1294 self.check_sendall_interrupted(False)
1221 1295
1222 def test_sendall_interrupted_with_timeout(self): 1296 def test_sendall_interrupted_with_timeout(self):
1223 self.check_sendall_interrupted(True) 1297 self.check_sendall_interrupted(True)
1224 1298
(...skipping 30 matching lines...) Expand all
1255 self.assertRaises(ValueError, fp.readable) 1329 self.assertRaises(ValueError, fp.readable)
1256 self.assertRaises(ValueError, fp.writable) 1330 self.assertRaises(ValueError, fp.writable)
1257 self.assertRaises(ValueError, fp.seekable) 1331 self.assertRaises(ValueError, fp.seekable)
1258 1332
1259 def test_pickle(self): 1333 def test_pickle(self):
1260 sock = socket.socket() 1334 sock = socket.socket()
1261 with sock: 1335 with sock:
1262 for protocol in range(pickle.HIGHEST_PROTOCOL + 1): 1336 for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
1263 self.assertRaises(TypeError, pickle.dumps, sock, protocol) 1337 self.assertRaises(TypeError, pickle.dumps, sock, protocol)
1264 1338
1265 def test_listen_backlog0(self): 1339 def test_listen_backlog(self):
1340 for backlog in 0, -1:
1341 srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1342 srv.bind((HOST, 0))
1343 srv.listen(backlog)
1344 srv.close()
1345
1346 @support.cpython_only
1347 def test_listen_backlog_overflow(self):
1348 # Issue 15989
1349 import _testcapi
1266 srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 1350 srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1267 srv.bind((HOST, 0)) 1351 srv.bind((HOST, 0))
1268 # backlog = 0 1352 self.assertRaises(OverflowError, srv.listen, _testcapi.INT_MAX + 1)
1269 srv.listen(0)
1270 srv.close() 1353 srv.close()
1271 1354
1272 @unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.') 1355 @unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.')
1273 def test_flowinfo(self): 1356 def test_flowinfo(self):
1274 self.assertRaises(OverflowError, socket.getnameinfo, 1357 self.assertRaises(OverflowError, socket.getnameinfo,
1275 ('::1',0, 0xffffffff), 0) 1358 (support.HOSTv6, 0, 0xffffffff), 0)
1276 with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s: 1359 with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s:
1277 self.assertRaises(OverflowError, s.bind, ('::1', 0, -10)) 1360 self.assertRaises(OverflowError, s.bind, (support.HOSTv6, 0, -10))
1278 1361
1362 def test_str_for_enums(self):
1363 # Make sure that the AF_* and SOCK_* constants have enum-like string
1364 # reprs.
1365 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
1366 self.assertEqual(str(s.family), 'AddressFamily.AF_INET')
1367 self.assertEqual(str(s.type), 'SocketType.SOCK_STREAM')
1368
1369 @unittest.skipIf(os.name == 'nt', 'Will not work on Windows')
1370 def test_uknown_socket_family_repr(self):
1371 # Test that when created with a family that's not one of the known
1372 # AF_*/SOCK_* constants, socket.family just returns the number.
1373 #
1374 # To do this we fool socket.socket into believing it already has an
1375 # open fd because on this path it doesn't actually verify the family and
1376 # type and populates the socket object.
1377 #
1378 # On Windows this trick won't work, so the test is skipped.
1379 fd, _ = tempfile.mkstemp()
1380 with socket.socket(family=42424, type=13331, fileno=fd) as s:
1381 self.assertEqual(s.family, 42424)
1382 self.assertEqual(s.type, 13331)
1279 1383
1280 @unittest.skipUnless(HAVE_SOCKET_CAN, 'SocketCan required for this test.') 1384 @unittest.skipUnless(HAVE_SOCKET_CAN, 'SocketCan required for this test.')
1281 class BasicCANTest(unittest.TestCase): 1385 class BasicCANTest(unittest.TestCase):
1282 1386
1283 def testCrucialConstants(self): 1387 def testCrucialConstants(self):
1284 socket.AF_CAN 1388 socket.AF_CAN
1285 socket.PF_CAN 1389 socket.PF_CAN
1286 socket.CAN_RAW 1390 socket.CAN_RAW
1287 1391
1392 @unittest.skipUnless(hasattr(socket, "CAN_BCM"),
1393 'socket.CAN_BCM required for this test.')
1394 def testBCMConstants(self):
1395 socket.CAN_BCM
1396
1397 # opcodes
1398 socket.CAN_BCM_TX_SETUP # create (cyclic) transmission task
1399 socket.CAN_BCM_TX_DELETE # remove (cyclic) transmission task
1400 socket.CAN_BCM_TX_READ # read properties of (cyclic) transmission t ask
1401 socket.CAN_BCM_TX_SEND # send one CAN frame
1402 socket.CAN_BCM_RX_SETUP # create RX content filter subscription
1403 socket.CAN_BCM_RX_DELETE # remove RX content filter subscription
1404 socket.CAN_BCM_RX_READ # read properties of RX content filter subsc ription
1405 socket.CAN_BCM_TX_STATUS # reply to TX_READ request
1406 socket.CAN_BCM_TX_EXPIRED # notification on performed transmissions (c ount=0)
1407 socket.CAN_BCM_RX_STATUS # reply to RX_READ request
1408 socket.CAN_BCM_RX_TIMEOUT # cyclic message is absent
1409 socket.CAN_BCM_RX_CHANGED # updated CAN frame (detected content change )
1410
1288 def testCreateSocket(self): 1411 def testCreateSocket(self):
1289 with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s: 1412 with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
1290 pass 1413 pass
1291 1414
1415 @unittest.skipUnless(hasattr(socket, "CAN_BCM"),
1416 'socket.CAN_BCM required for this test.')
1417 def testCreateBCMSocket(self):
1418 with socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_BCM) as s:
1419 pass
1420
1292 def testBindAny(self): 1421 def testBindAny(self):
1293 with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s: 1422 with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
1294 s.bind(('', )) 1423 s.bind(('', ))
1295 1424
1296 def testTooLongInterfaceName(self): 1425 def testTooLongInterfaceName(self):
1297 # most systems limit IFNAMSIZ to 16, take 1024 to be sure 1426 # most systems limit IFNAMSIZ to 16, take 1024 to be sure
1298 with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s: 1427 with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
1299 self.assertRaisesRegex(socket.error, 'interface name too long', 1428 self.assertRaisesRegex(OSError, 'interface name too long',
1300 s.bind, ('x' * 1024,)) 1429 s.bind, ('x' * 1024,))
1301 1430
1302 @unittest.skipUnless(hasattr(socket, "CAN_RAW_LOOPBACK"), 1431 @unittest.skipUnless(hasattr(socket, "CAN_RAW_LOOPBACK"),
1303 'socket.CAN_RAW_LOOPBACK required for this test.') 1432 'socket.CAN_RAW_LOOPBACK required for this test.')
1304 def testLoopback(self): 1433 def testLoopback(self):
1305 with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s: 1434 with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
1306 for loopback in (0, 1): 1435 for loopback in (0, 1):
1307 s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_LOOPBACK, 1436 s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_LOOPBACK,
1308 loopback) 1437 loopback)
1309 self.assertEqual(loopback, 1438 self.assertEqual(loopback,
1310 s.getsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_LOOPBACK)) 1439 s.getsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_LOOPBACK))
1311 1440
1312 @unittest.skipUnless(hasattr(socket, "CAN_RAW_FILTER"), 1441 @unittest.skipUnless(hasattr(socket, "CAN_RAW_FILTER"),
1313 'socket.CAN_RAW_FILTER required for this test.') 1442 'socket.CAN_RAW_FILTER required for this test.')
1314 def testFilter(self): 1443 def testFilter(self):
1315 can_id, can_mask = 0x200, 0x700 1444 can_id, can_mask = 0x200, 0x700
1316 can_filter = struct.pack("=II", can_id, can_mask) 1445 can_filter = struct.pack("=II", can_id, can_mask)
1317 with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s: 1446 with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
1318 s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FILTER, can_filter) 1447 s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FILTER, can_filter)
1319 self.assertEqual(can_filter, 1448 self.assertEqual(can_filter,
1320 s.getsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FILTER, 8)) 1449 s.getsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FILTER, 8))
1321 1450
1322 1451
1323 @unittest.skipUnless(HAVE_SOCKET_CAN, 'SocketCan required for this test.') 1452 @unittest.skipUnless(HAVE_SOCKET_CAN, 'SocketCan required for this test.')
1324 @unittest.skipUnless(thread, 'Threading required for this test.')
1325 class CANTest(ThreadedCANSocketTest): 1453 class CANTest(ThreadedCANSocketTest):
1326
1327 """The CAN frame structure is defined in <linux/can.h>:
1328
1329 struct can_frame {
1330 canid_t can_id; /* 32 bit CAN_ID + EFF/RTR/ERR flags */
1331 __u8 can_dlc; /* data length code: 0 .. 8 */
1332 __u8 data[8] __attribute__((aligned(8)));
1333 };
1334 """
1335 can_frame_fmt = "=IB3x8s"
1336 1454
1337 def __init__(self, methodName='runTest'): 1455 def __init__(self, methodName='runTest'):
1338 ThreadedCANSocketTest.__init__(self, methodName=methodName) 1456 ThreadedCANSocketTest.__init__(self, methodName=methodName)
1339 1457
1340 @classmethod 1458 @classmethod
1341 def build_can_frame(cls, can_id, data): 1459 def build_can_frame(cls, can_id, data):
1342 """Build a CAN frame.""" 1460 """Build a CAN frame."""
1343 can_dlc = len(data) 1461 can_dlc = len(data)
1344 data = data.ljust(8, b'\x00') 1462 data = data.ljust(8, b'\x00')
1345 return struct.pack(cls.can_frame_fmt, can_id, can_dlc, data) 1463 return struct.pack(cls.can_frame_fmt, can_id, can_dlc, data)
(...skipping 28 matching lines...) Expand all
1374 1492
1375 cf, addr = self.s.recvfrom(self.bufsize) 1493 cf, addr = self.s.recvfrom(self.bufsize)
1376 self.assertEqual(self.cf2, cf) 1494 self.assertEqual(self.cf2, cf)
1377 1495
1378 def _testSendMultiFrames(self): 1496 def _testSendMultiFrames(self):
1379 self.cf1 = self.build_can_frame(0x07, b'\x44\x33\x22\x11') 1497 self.cf1 = self.build_can_frame(0x07, b'\x44\x33\x22\x11')
1380 self.cli.send(self.cf1) 1498 self.cli.send(self.cf1)
1381 1499
1382 self.cf2 = self.build_can_frame(0x12, b'\x99\x22\x33') 1500 self.cf2 = self.build_can_frame(0x12, b'\x99\x22\x33')
1383 self.cli.send(self.cf2) 1501 self.cli.send(self.cf2)
1502
1503 @unittest.skipUnless(hasattr(socket, "CAN_BCM"),
1504 'socket.CAN_BCM required for this test.')
1505 def _testBCM(self):
1506 cf, addr = self.cli.recvfrom(self.bufsize)
1507 self.assertEqual(self.cf, cf)
1508 can_id, can_dlc, data = self.dissect_can_frame(cf)
1509 self.assertEqual(self.can_id, can_id)
1510 self.assertEqual(self.data, data)
1511
1512 @unittest.skipUnless(hasattr(socket, "CAN_BCM"),
1513 'socket.CAN_BCM required for this test.')
1514 def testBCM(self):
1515 bcm = socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_BCM)
1516 self.addCleanup(bcm.close)
1517 bcm.connect((self.interface,))
1518 self.can_id = 0x123
1519 self.data = bytes([0xc0, 0xff, 0xee])
1520 self.cf = self.build_can_frame(self.can_id, self.data)
1521 opcode = socket.CAN_BCM_TX_SEND
1522 flags = 0
1523 count = 0
1524 ival1_seconds = ival1_usec = ival2_seconds = ival2_usec = 0
1525 bcm_can_id = 0x0222
1526 nframes = 1
1527 assert len(self.cf) == 16
1528 header = struct.pack(self.bcm_cmd_msg_fmt,
1529 opcode,
1530 flags,
1531 count,
1532 ival1_seconds,
1533 ival1_usec,
1534 ival2_seconds,
1535 ival2_usec,
1536 bcm_can_id,
1537 nframes,
1538 )
1539 header_plus_frame = header + self.cf
1540 bytes_sent = bcm.send(header_plus_frame)
1541 self.assertEqual(bytes_sent, len(header_plus_frame))
1384 1542
1385 1543
1386 @unittest.skipUnless(HAVE_SOCKET_RDS, 'RDS sockets required for this test.') 1544 @unittest.skipUnless(HAVE_SOCKET_RDS, 'RDS sockets required for this test.')
1387 class BasicRDSTest(unittest.TestCase): 1545 class BasicRDSTest(unittest.TestCase):
1388 1546
1389 def testCrucialConstants(self): 1547 def testCrucialConstants(self):
1390 socket.AF_RDS 1548 socket.AF_RDS
1391 socket.PF_RDS 1549 socket.PF_RDS
1392 1550
1393 def testCreateSocket(self): 1551 def testCreateSocket(self):
(...skipping 183 matching lines...) Expand 10 before | Expand all | Expand 10 after
1577 self.assertEqual(msg, MSG) 1735 self.assertEqual(msg, MSG)
1578 # wait for _testShutdown to finish: on OS X, when the server 1736 # wait for _testShutdown to finish: on OS X, when the server
1579 # closes the connection the client also becomes disconnected, 1737 # closes the connection the client also becomes disconnected,
1580 # and the client's shutdown call will fail. (Issue #4397.) 1738 # and the client's shutdown call will fail. (Issue #4397.)
1581 self.done.wait() 1739 self.done.wait()
1582 1740
1583 def _testShutdown(self): 1741 def _testShutdown(self):
1584 self.serv_conn.send(MSG) 1742 self.serv_conn.send(MSG)
1585 self.serv_conn.shutdown(2) 1743 self.serv_conn.shutdown(2)
1586 1744
1745 testShutdown_overflow = support.cpython_only(testShutdown)
1746
1747 @support.cpython_only
1748 def _testShutdown_overflow(self):
1749 import _testcapi
1750 self.serv_conn.send(MSG)
1751 # Issue 15989
1752 self.assertRaises(OverflowError, self.serv_conn.shutdown,
1753 _testcapi.INT_MAX + 1)
1754 self.assertRaises(OverflowError, self.serv_conn.shutdown,
1755 2 + (_testcapi.UINT_MAX + 1))
1756 self.serv_conn.shutdown(2)
1757
1587 def testDetach(self): 1758 def testDetach(self):
1588 # Testing detach() 1759 # Testing detach()
1589 fileno = self.cli_conn.fileno() 1760 fileno = self.cli_conn.fileno()
1590 f = self.cli_conn.detach() 1761 f = self.cli_conn.detach()
1591 self.assertEqual(f, fileno) 1762 self.assertEqual(f, fileno)
1592 # cli_conn cannot be used anymore... 1763 # cli_conn cannot be used anymore...
1593 self.assertTrue(self.cli_conn._closed) 1764 self.assertTrue(self.cli_conn._closed)
1594 self.assertRaises(socket.error, self.cli_conn.recv, 1024) 1765 self.assertRaises(OSError, self.cli_conn.recv, 1024)
1595 self.cli_conn.close() 1766 self.cli_conn.close()
1596 # ...but we can create another socket using the (still open) 1767 # ...but we can create another socket using the (still open)
1597 # file descriptor 1768 # file descriptor
1598 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, fileno=f) 1769 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, fileno=f)
1599 self.addCleanup(sock.close) 1770 self.addCleanup(sock.close)
1600 msg = sock.recv(1024) 1771 msg = sock.recv(1024)
1601 self.assertEqual(msg, MSG) 1772 self.assertEqual(msg, MSG)
1602 1773
1603 def _testDetach(self): 1774 def _testDetach(self):
1604 self.serv_conn.send(MSG) 1775 self.serv_conn.send(MSG)
(...skipping 348 matching lines...) Expand 10 before | Expand all | Expand 10 after
1953 self.sendToServer(b"done") 2124 self.sendToServer(b"done")
1954 2125
1955 def testSendmsgExcessCmsgReject(self): 2126 def testSendmsgExcessCmsgReject(self):
1956 # Check that sendmsg() rejects excess ancillary data items 2127 # Check that sendmsg() rejects excess ancillary data items
1957 # when the number that can be sent is limited. 2128 # when the number that can be sent is limited.
1958 self.assertEqual(self.serv_sock.recv(1000), b"done") 2129 self.assertEqual(self.serv_sock.recv(1000), b"done")
1959 2130
1960 def _testSendmsgExcessCmsgReject(self): 2131 def _testSendmsgExcessCmsgReject(self):
1961 if not hasattr(socket, "CMSG_SPACE"): 2132 if not hasattr(socket, "CMSG_SPACE"):
1962 # Can only send one item 2133 # Can only send one item
1963 with self.assertRaises(socket.error) as cm: 2134 with self.assertRaises(OSError) as cm:
1964 self.sendmsgToServer([MSG], [(0, 0, b""), (0, 0, b"")]) 2135 self.sendmsgToServer([MSG], [(0, 0, b""), (0, 0, b"")])
1965 self.assertIsNone(cm.exception.errno) 2136 self.assertIsNone(cm.exception.errno)
1966 self.sendToServer(b"done") 2137 self.sendToServer(b"done")
1967 2138
1968 def testSendmsgAfterClose(self): 2139 def testSendmsgAfterClose(self):
1969 # Check that sendmsg() fails on a closed socket. 2140 # Check that sendmsg() fails on a closed socket.
1970 pass 2141 pass
1971 2142
1972 def _testSendmsgAfterClose(self): 2143 def _testSendmsgAfterClose(self):
1973 self.cli_sock.close() 2144 self.cli_sock.close()
1974 self.assertRaises(socket.error, self.sendmsgToServer, [MSG]) 2145 self.assertRaises(OSError, self.sendmsgToServer, [MSG])
1975 2146
1976 2147
1977 class SendmsgStreamTests(SendmsgTests): 2148 class SendmsgStreamTests(SendmsgTests):
1978 # Tests for sendmsg() which require a stream socket and do not 2149 # Tests for sendmsg() which require a stream socket and do not
1979 # involve recvmsg() or recvmsg_into(). 2150 # involve recvmsg() or recvmsg_into().
1980 2151
1981 def testSendmsgExplicitNoneAddr(self): 2152 def testSendmsgExplicitNoneAddr(self):
1982 # Check that peer address can be specified as None. 2153 # Check that peer address can be specified as None.
1983 self.assertEqual(self.serv_sock.recv(len(MSG)), MSG) 2154 self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
1984 2155
(...skipping 23 matching lines...) Expand all
2008 "MSG_DONTWAIT not known to work on this platform when " 2179 "MSG_DONTWAIT not known to work on this platform when "
2009 "sending") 2180 "sending")
2010 def testSendmsgDontWait(self): 2181 def testSendmsgDontWait(self):
2011 # Check that MSG_DONTWAIT in flags causes non-blocking behaviour. 2182 # Check that MSG_DONTWAIT in flags causes non-blocking behaviour.
2012 self.assertEqual(self.serv_sock.recv(512), b"a"*512) 2183 self.assertEqual(self.serv_sock.recv(512), b"a"*512)
2013 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) 2184 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
2014 2185
2015 @testSendmsgDontWait.client_skip 2186 @testSendmsgDontWait.client_skip
2016 def _testSendmsgDontWait(self): 2187 def _testSendmsgDontWait(self):
2017 try: 2188 try:
2018 with self.assertRaises(socket.error) as cm: 2189 with self.assertRaises(OSError) as cm:
2019 while True: 2190 while True:
2020 self.sendmsgToServer([b"a"*512], [], socket.MSG_DONTWAIT) 2191 self.sendmsgToServer([b"a"*512], [], socket.MSG_DONTWAIT)
2021 self.assertIn(cm.exception.errno, 2192 self.assertIn(cm.exception.errno,
2022 (errno.EAGAIN, errno.EWOULDBLOCK)) 2193 (errno.EAGAIN, errno.EWOULDBLOCK))
2023 finally: 2194 finally:
2024 self.misc_event.set() 2195 self.misc_event.set()
2025 2196
2026 2197
2027 class SendmsgConnectionlessTests(SendmsgTests): 2198 class SendmsgConnectionlessTests(SendmsgTests):
2028 # Tests for sendmsg() which require a connectionless-mode 2199 # Tests for sendmsg() which require a connectionless-mode
2029 # (e.g. datagram) socket, and do not involve recvmsg() or 2200 # (e.g. datagram) socket, and do not involve recvmsg() or
2030 # recvmsg_into(). 2201 # recvmsg_into().
2031 2202
2032 def testSendmsgNoDestAddr(self): 2203 def testSendmsgNoDestAddr(self):
2033 # Check that sendmsg() fails when no destination address is 2204 # Check that sendmsg() fails when no destination address is
2034 # given for unconnected socket. 2205 # given for unconnected socket.
2035 pass 2206 pass
2036 2207
2037 def _testSendmsgNoDestAddr(self): 2208 def _testSendmsgNoDestAddr(self):
2038 self.assertRaises(socket.error, self.cli_sock.sendmsg, 2209 self.assertRaises(OSError, self.cli_sock.sendmsg,
2039 [MSG]) 2210 [MSG])
2040 self.assertRaises(socket.error, self.cli_sock.sendmsg, 2211 self.assertRaises(OSError, self.cli_sock.sendmsg,
2041 [MSG], [], 0, None) 2212 [MSG], [], 0, None)
2042 2213
2043 2214
2044 class RecvmsgGenericTests(SendrecvmsgBase): 2215 class RecvmsgGenericTests(SendrecvmsgBase):
2045 # Tests for recvmsg() which can also be emulated using 2216 # Tests for recvmsg() which can also be emulated using
2046 # recvmsg_into(), and can use any socket type. 2217 # recvmsg_into(), and can use any socket type.
2047 2218
2048 def testRecvmsg(self): 2219 def testRecvmsg(self):
2049 # Receive a simple message with recvmsg[_into](). 2220 # Receive a simple message with recvmsg[_into]().
2050 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, len(MSG)) 2221 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, len(MSG))
(...skipping 65 matching lines...) Expand 10 before | Expand all | Expand 10 after
2116 self.checkRecvmsgAddress(addr, self.cli_addr) 2287 self.checkRecvmsgAddress(addr, self.cli_addr)
2117 self.assertEqual(ancdata, []) 2288 self.assertEqual(ancdata, [])
2118 self.checkFlags(flags, eor=True) 2289 self.checkFlags(flags, eor=True)
2119 2290
2120 def _testRecvmsgLongAncillaryBuf(self): 2291 def _testRecvmsgLongAncillaryBuf(self):
2121 self.sendToServer(MSG) 2292 self.sendToServer(MSG)
2122 2293
2123 def testRecvmsgAfterClose(self): 2294 def testRecvmsgAfterClose(self):
2124 # Check that recvmsg[_into]() fails on a closed socket. 2295 # Check that recvmsg[_into]() fails on a closed socket.
2125 self.serv_sock.close() 2296 self.serv_sock.close()
2126 self.assertRaises(socket.error, self.doRecvmsg, self.serv_sock, 1024) 2297 self.assertRaises(OSError, self.doRecvmsg, self.serv_sock, 1024)
2127 2298
2128 def _testRecvmsgAfterClose(self): 2299 def _testRecvmsgAfterClose(self):
2129 pass 2300 pass
2130 2301
2131 def testRecvmsgTimeout(self): 2302 def testRecvmsgTimeout(self):
2132 # Check that timeout works. 2303 # Check that timeout works.
2133 try: 2304 try:
2134 self.serv_sock.settimeout(0.03) 2305 self.serv_sock.settimeout(0.03)
2135 self.assertRaises(socket.timeout, 2306 self.assertRaises(socket.timeout,
2136 self.doRecvmsg, self.serv_sock, len(MSG)) 2307 self.doRecvmsg, self.serv_sock, len(MSG))
(...skipping 201 matching lines...) Expand 10 before | Expand all | Expand 10 after
2338 def _testRecvmsgIntoScatter(self): 2509 def _testRecvmsgIntoScatter(self):
2339 self.sendToServer(b"Mary had a little lamb") 2510 self.sendToServer(b"Mary had a little lamb")
2340 2511
2341 2512
2342 class CmsgMacroTests(unittest.TestCase): 2513 class CmsgMacroTests(unittest.TestCase):
2343 # Test the functions CMSG_LEN() and CMSG_SPACE(). Tests 2514 # Test the functions CMSG_LEN() and CMSG_SPACE(). Tests
2344 # assumptions used by sendmsg() and recvmsg[_into](), which share 2515 # assumptions used by sendmsg() and recvmsg[_into](), which share
2345 # code with these functions. 2516 # code with these functions.
2346 2517
2347 # Match the definition in socketmodule.c 2518 # Match the definition in socketmodule.c
2348 socklen_t_limit = min(0x7fffffff, _testcapi.INT_MAX) 2519 try:
2520 import _testcapi
2521 except ImportError:
2522 socklen_t_limit = 0x7fffffff
2523 else:
2524 socklen_t_limit = min(0x7fffffff, _testcapi.INT_MAX)
2349 2525
2350 @requireAttrs(socket, "CMSG_LEN") 2526 @requireAttrs(socket, "CMSG_LEN")
2351 def testCMSG_LEN(self): 2527 def testCMSG_LEN(self):
2352 # Test CMSG_LEN() with various valid and invalid values, 2528 # Test CMSG_LEN() with various valid and invalid values,
2353 # checking the assumptions used by recvmsg() and sendmsg(). 2529 # checking the assumptions used by recvmsg() and sendmsg().
2354 toobig = self.socklen_t_limit - socket.CMSG_LEN(0) + 1 2530 toobig = self.socklen_t_limit - socket.CMSG_LEN(0) + 1
2355 values = list(range(257)) + list(range(toobig - 257, toobig)) 2531 values = list(range(257)) + list(range(toobig - 257, toobig))
2356 2532
2357 # struct cmsghdr has at least three members, two of which are ints 2533 # struct cmsghdr has at least three members, two of which are ints
2358 self.assertGreater(socket.CMSG_LEN(0), array.array("i").itemsize * 2) 2534 self.assertGreater(socket.CMSG_LEN(0), array.array("i").itemsize * 2)
(...skipping 152 matching lines...) Expand 10 before | Expand all | Expand 10 after
2511 self.doRecvmsg(self.serv_sock, len(MSG), 2687 self.doRecvmsg(self.serv_sock, len(MSG),
2512 socket.CMSG_LEN(4 * SIZEOF_INT)), 2688 socket.CMSG_LEN(4 * SIZEOF_INT)),
2513 # RFC 3542 says implementations may set 2689 # RFC 3542 says implementations may set
2514 # MSG_CTRUNC if there isn't enough space 2690 # MSG_CTRUNC if there isn't enough space
2515 # for trailing padding. 2691 # for trailing padding.
2516 ignoreflags=socket.MSG_CTRUNC) 2692 ignoreflags=socket.MSG_CTRUNC)
2517 2693
2518 def _testFDPassCMSG_LEN(self): 2694 def _testFDPassCMSG_LEN(self):
2519 self.createAndSendFDs(1) 2695 self.createAndSendFDs(1)
2520 2696
2521 # Issue #12958: The following test has problems on Mac OS X 2697 @unittest.skipIf(sys.platform == "darwin", "skipping, see issue #12958")
2522 @support.anticipate_failure(sys.platform == "darwin")
2523 @requireAttrs(socket, "CMSG_SPACE") 2698 @requireAttrs(socket, "CMSG_SPACE")
2524 def testFDPassSeparate(self): 2699 def testFDPassSeparate(self):
2525 # Pass two FDs in two separate arrays. Arrays may be combined 2700 # Pass two FDs in two separate arrays. Arrays may be combined
2526 # into a single control message by the OS. 2701 # into a single control message by the OS.
2527 self.checkRecvmsgFDs(2, 2702 self.checkRecvmsgFDs(2,
2528 self.doRecvmsg(self.serv_sock, len(MSG), 10240), 2703 self.doRecvmsg(self.serv_sock, len(MSG), 10240),
2529 maxcmsgs=2) 2704 maxcmsgs=2)
2530 2705
2531 @testFDPassSeparate.client_skip 2706 @testFDPassSeparate.client_skip
2532 @support.anticipate_failure(sys.platform == "darwin") 2707 @unittest.skipIf(sys.platform == "darwin", "skipping, see issue #12958")
2533 def _testFDPassSeparate(self): 2708 def _testFDPassSeparate(self):
2534 fd0, fd1 = self.newFDs(2) 2709 fd0, fd1 = self.newFDs(2)
2535 self.assertEqual( 2710 self.assertEqual(
2536 self.sendmsgToServer([MSG], [(socket.SOL_SOCKET, 2711 self.sendmsgToServer([MSG], [(socket.SOL_SOCKET,
2537 socket.SCM_RIGHTS, 2712 socket.SCM_RIGHTS,
2538 array.array("i", [fd0])), 2713 array.array("i", [fd0])),
2539 (socket.SOL_SOCKET, 2714 (socket.SOL_SOCKET,
2540 socket.SCM_RIGHTS, 2715 socket.SCM_RIGHTS,
2541 array.array("i", [fd1]))]), 2716 array.array("i", [fd1]))]),
2542 len(MSG)) 2717 len(MSG))
2543 2718
2544 # Issue #12958: The following test has problems on Mac OS X 2719 @unittest.skipIf(sys.platform == "darwin", "skipping, see issue #12958")
2545 @support.anticipate_failure(sys.platform == "darwin")
2546 @requireAttrs(socket, "CMSG_SPACE") 2720 @requireAttrs(socket, "CMSG_SPACE")
2547 def testFDPassSeparateMinSpace(self): 2721 def testFDPassSeparateMinSpace(self):
2548 # Pass two FDs in two separate arrays, receiving them into the 2722 # Pass two FDs in two separate arrays, receiving them into the
2549 # minimum space for two arrays. 2723 # minimum space for two arrays.
2550 self.checkRecvmsgFDs(2, 2724 self.checkRecvmsgFDs(2,
2551 self.doRecvmsg(self.serv_sock, len(MSG), 2725 self.doRecvmsg(self.serv_sock, len(MSG),
2552 socket.CMSG_SPACE(SIZEOF_INT) + 2726 socket.CMSG_SPACE(SIZEOF_INT) +
2553 socket.CMSG_LEN(SIZEOF_INT)), 2727 socket.CMSG_LEN(SIZEOF_INT)),
2554 maxcmsgs=2, ignoreflags=socket.MSG_CTRUNC) 2728 maxcmsgs=2, ignoreflags=socket.MSG_CTRUNC)
2555 2729
2556 @testFDPassSeparateMinSpace.client_skip 2730 @testFDPassSeparateMinSpace.client_skip
2557 @support.anticipate_failure(sys.platform == "darwin") 2731 @unittest.skipIf(sys.platform == "darwin", "skipping, see issue #12958")
2558 def _testFDPassSeparateMinSpace(self): 2732 def _testFDPassSeparateMinSpace(self):
2559 fd0, fd1 = self.newFDs(2) 2733 fd0, fd1 = self.newFDs(2)
2560 self.assertEqual( 2734 self.assertEqual(
2561 self.sendmsgToServer([MSG], [(socket.SOL_SOCKET, 2735 self.sendmsgToServer([MSG], [(socket.SOL_SOCKET,
2562 socket.SCM_RIGHTS, 2736 socket.SCM_RIGHTS,
2563 array.array("i", [fd0])), 2737 array.array("i", [fd0])),
2564 (socket.SOL_SOCKET, 2738 (socket.SOL_SOCKET,
2565 socket.SCM_RIGHTS, 2739 socket.SCM_RIGHTS,
2566 array.array("i", [fd1]))]), 2740 array.array("i", [fd1]))]),
2567 len(MSG)) 2741 len(MSG))
2568 2742
2569 def sendAncillaryIfPossible(self, msg, ancdata): 2743 def sendAncillaryIfPossible(self, msg, ancdata):
2570 # Try to send msg and ancdata to server, but if the system 2744 # Try to send msg and ancdata to server, but if the system
2571 # call fails, just send msg with no ancillary data. 2745 # call fails, just send msg with no ancillary data.
2572 try: 2746 try:
2573 nbytes = self.sendmsgToServer([msg], ancdata) 2747 nbytes = self.sendmsgToServer([msg], ancdata)
2574 except socket.error as e: 2748 except OSError as e:
2575 # Check that it was the system call that failed 2749 # Check that it was the system call that failed
2576 self.assertIsInstance(e.errno, int) 2750 self.assertIsInstance(e.errno, int)
2577 nbytes = self.sendmsgToServer([msg]) 2751 nbytes = self.sendmsgToServer([msg])
2578 self.assertEqual(nbytes, len(msg)) 2752 self.assertEqual(nbytes, len(msg))
2579 2753
2580 def testFDPassEmpty(self): 2754 def testFDPassEmpty(self):
2581 # Try to pass an empty FD array. Can receive either no array 2755 # Try to pass an empty FD array. Can receive either no array
2582 # or an empty array. 2756 # or an empty array.
2583 self.checkRecvmsgFDs(0, self.doRecvmsg(self.serv_sock, 2757 self.checkRecvmsgFDs(0, self.doRecvmsg(self.serv_sock,
2584 len(MSG), 10240), 2758 len(MSG), 10240),
(...skipping 357 matching lines...) Expand 10 before | Expand all | Expand 10 after
2942 @testOddCmsgSize.client_skip 3116 @testOddCmsgSize.client_skip
2943 def _testOddCmsgSize(self): 3117 def _testOddCmsgSize(self):
2944 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) 3118 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
2945 try: 3119 try:
2946 nbytes = self.sendmsgToServer( 3120 nbytes = self.sendmsgToServer(
2947 [MSG], 3121 [MSG],
2948 [(socket.IPPROTO_IPV6, socket.IPV6_TCLASS, 3122 [(socket.IPPROTO_IPV6, socket.IPV6_TCLASS,
2949 array.array("i", [self.traffic_class]).tobytes() + b"\x00"), 3123 array.array("i", [self.traffic_class]).tobytes() + b"\x00"),
2950 (socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT, 3124 (socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT,
2951 array.array("i", [self.hop_limit]))]) 3125 array.array("i", [self.hop_limit]))])
2952 except socket.error as e: 3126 except OSError as e:
2953 self.assertIsInstance(e.errno, int) 3127 self.assertIsInstance(e.errno, int)
2954 nbytes = self.sendmsgToServer( 3128 nbytes = self.sendmsgToServer(
2955 [MSG], 3129 [MSG],
2956 [(socket.IPPROTO_IPV6, socket.IPV6_TCLASS, 3130 [(socket.IPPROTO_IPV6, socket.IPV6_TCLASS,
2957 array.array("i", [self.traffic_class])), 3131 array.array("i", [self.traffic_class])),
2958 (socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT, 3132 (socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT,
2959 array.array("i", [self.hop_limit]))]) 3133 array.array("i", [self.hop_limit]))])
2960 self.assertEqual(nbytes, len(MSG)) 3134 self.assertEqual(nbytes, len(MSG))
2961 3135
2962 # Tests for proper handling of truncated ancillary data 3136 # Tests for proper handling of truncated ancillary data
(...skipping 240 matching lines...) Expand 10 before | Expand all | Expand 10 after
3203 3377
3204 @requireAttrs(socket.socket, "recvmsg_into") 3378 @requireAttrs(socket.socket, "recvmsg_into")
3205 @unittest.skipUnless(thread, 'Threading required for this test.') 3379 @unittest.skipUnless(thread, 'Threading required for this test.')
3206 class RecvmsgIntoUDPTest(RecvmsgIntoTests, SendrecvmsgUDPTestBase): 3380 class RecvmsgIntoUDPTest(RecvmsgIntoTests, SendrecvmsgUDPTestBase):
3207 pass 3381 pass
3208 3382
3209 3383
3210 class SendrecvmsgUDP6TestBase(SendrecvmsgDgramFlagsBase, 3384 class SendrecvmsgUDP6TestBase(SendrecvmsgDgramFlagsBase,
3211 SendrecvmsgConnectionlessBase, 3385 SendrecvmsgConnectionlessBase,
3212 ThreadedSocketTestMixin, UDP6TestBase): 3386 ThreadedSocketTestMixin, UDP6TestBase):
3213 pass 3387
3388 def checkRecvmsgAddress(self, addr1, addr2):
3389 # Called to compare the received address with the address of
3390 # the peer, ignoring scope ID
3391 self.assertEqual(addr1[:-1], addr2[:-1])
3214 3392
3215 @requireAttrs(socket.socket, "sendmsg") 3393 @requireAttrs(socket.socket, "sendmsg")
3216 @unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.') 3394 @unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.')
3217 @requireSocket("AF_INET6", "SOCK_DGRAM") 3395 @requireSocket("AF_INET6", "SOCK_DGRAM")
3218 @unittest.skipUnless(thread, 'Threading required for this test.') 3396 @unittest.skipUnless(thread, 'Threading required for this test.')
3219 class SendmsgUDP6Test(SendmsgConnectionlessTests, SendrecvmsgUDP6TestBase): 3397 class SendmsgUDP6Test(SendmsgConnectionlessTests, SendrecvmsgUDP6TestBase):
3220 pass 3398 pass
3221 3399
3222 @requireAttrs(socket.socket, "recvmsg") 3400 @requireAttrs(socket.socket, "recvmsg")
3223 @unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.') 3401 @unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.')
(...skipping 60 matching lines...) Expand 10 before | Expand all | Expand 10 after
3284 @requireSocket("AF_INET", "SOCK_STREAM", "IPPROTO_SCTP") 3462 @requireSocket("AF_INET", "SOCK_STREAM", "IPPROTO_SCTP")
3285 @unittest.skipUnless(thread, 'Threading required for this test.') 3463 @unittest.skipUnless(thread, 'Threading required for this test.')
3286 class SendmsgSCTPStreamTest(SendmsgStreamTests, SendrecvmsgSCTPStreamTestBase): 3464 class SendmsgSCTPStreamTest(SendmsgStreamTests, SendrecvmsgSCTPStreamTestBase):
3287 pass 3465 pass
3288 3466
3289 @requireAttrs(socket.socket, "recvmsg") 3467 @requireAttrs(socket.socket, "recvmsg")
3290 @requireSocket("AF_INET", "SOCK_STREAM", "IPPROTO_SCTP") 3468 @requireSocket("AF_INET", "SOCK_STREAM", "IPPROTO_SCTP")
3291 @unittest.skipUnless(thread, 'Threading required for this test.') 3469 @unittest.skipUnless(thread, 'Threading required for this test.')
3292 class RecvmsgSCTPStreamTest(RecvmsgTests, RecvmsgGenericStreamTests, 3470 class RecvmsgSCTPStreamTest(RecvmsgTests, RecvmsgGenericStreamTests,
3293 SendrecvmsgSCTPStreamTestBase): 3471 SendrecvmsgSCTPStreamTestBase):
3294 pass 3472
3473 def testRecvmsgEOF(self):
3474 try:
3475 super(RecvmsgSCTPStreamTest, self).testRecvmsgEOF()
3476 except OSError as e:
3477 if e.errno != errno.ENOTCONN:
3478 raise
3479 self.skipTest("sporadic ENOTCONN (kernel issue?) - see issue #13876" )
3295 3480
3296 @requireAttrs(socket.socket, "recvmsg_into") 3481 @requireAttrs(socket.socket, "recvmsg_into")
3297 @requireSocket("AF_INET", "SOCK_STREAM", "IPPROTO_SCTP") 3482 @requireSocket("AF_INET", "SOCK_STREAM", "IPPROTO_SCTP")
3298 @unittest.skipUnless(thread, 'Threading required for this test.') 3483 @unittest.skipUnless(thread, 'Threading required for this test.')
3299 class RecvmsgIntoSCTPStreamTest(RecvmsgIntoTests, RecvmsgGenericStreamTests, 3484 class RecvmsgIntoSCTPStreamTest(RecvmsgIntoTests, RecvmsgGenericStreamTests,
3300 SendrecvmsgSCTPStreamTestBase): 3485 SendrecvmsgSCTPStreamTestBase):
3301 pass 3486
3487 def testRecvmsgEOF(self):
3488 try:
3489 super(RecvmsgIntoSCTPStreamTest, self).testRecvmsgEOF()
3490 except OSError as e:
3491 if e.errno != errno.ENOTCONN:
3492 raise
3493 self.skipTest("sporadic ENOTCONN (kernel issue?) - see issue #13876" )
3302 3494
3303 3495
3304 class SendrecvmsgUnixStreamTestBase(SendrecvmsgConnectedBase, 3496 class SendrecvmsgUnixStreamTestBase(SendrecvmsgConnectedBase,
3305 ConnectedStreamTestMixin, UnixStreamBase): 3497 ConnectedStreamTestMixin, UnixStreamBase):
3306 pass 3498 pass
3307 3499
3308 @requireAttrs(socket.socket, "sendmsg") 3500 @requireAttrs(socket.socket, "sendmsg")
3309 @requireAttrs(socket, "AF_UNIX") 3501 @requireAttrs(socket, "AF_UNIX")
3310 @unittest.skipUnless(thread, 'Threading required for this test.') 3502 @unittest.skipUnless(thread, 'Threading required for this test.')
3311 class SendmsgUnixStreamTest(SendmsgStreamTests, SendrecvmsgUnixStreamTestBase): 3503 class SendmsgUnixStreamTest(SendmsgStreamTests, SendrecvmsgUnixStreamTestBase):
(...skipping 70 matching lines...) Expand 10 before | Expand all | Expand 10 after
3382 "Don't have signal.alarm or signal.setitimer") 3574 "Don't have signal.alarm or signal.setitimer")
3383 class InterruptedRecvTimeoutTest(InterruptedTimeoutBase, UDPTestBase): 3575 class InterruptedRecvTimeoutTest(InterruptedTimeoutBase, UDPTestBase):
3384 # Test interrupting the recv*() methods with signals when a 3576 # Test interrupting the recv*() methods with signals when a
3385 # timeout is set. 3577 # timeout is set.
3386 3578
3387 def setUp(self): 3579 def setUp(self):
3388 super().setUp() 3580 super().setUp()
3389 self.serv.settimeout(self.timeout) 3581 self.serv.settimeout(self.timeout)
3390 3582
3391 def checkInterruptedRecv(self, func, *args, **kwargs): 3583 def checkInterruptedRecv(self, func, *args, **kwargs):
3392 # Check that func(*args, **kwargs) raises socket.error with an 3584 # Check that func(*args, **kwargs) raises OSError with an
3393 # errno of EINTR when interrupted by a signal. 3585 # errno of EINTR when interrupted by a signal.
3394 self.setAlarm(self.alarm_time) 3586 self.setAlarm(self.alarm_time)
3395 with self.assertRaises(socket.error) as cm: 3587 with self.assertRaises(OSError) as cm:
3396 func(*args, **kwargs) 3588 func(*args, **kwargs)
3397 self.assertNotIsInstance(cm.exception, socket.timeout) 3589 self.assertNotIsInstance(cm.exception, socket.timeout)
3398 self.assertEqual(cm.exception.errno, errno.EINTR) 3590 self.assertEqual(cm.exception.errno, errno.EINTR)
3399 3591
3400 def testInterruptedRecvTimeout(self): 3592 def testInterruptedRecvTimeout(self):
3401 self.checkInterruptedRecv(self.serv.recv, 1024) 3593 self.checkInterruptedRecv(self.serv.recv, 1024)
3402 3594
3403 def testInterruptedRecvIntoTimeout(self): 3595 def testInterruptedRecvIntoTimeout(self):
3404 self.checkInterruptedRecv(self.serv.recv_into, bytearray(1024)) 3596 self.checkInterruptedRecv(self.serv.recv_into, bytearray(1024))
3405 3597
(...skipping 36 matching lines...) Expand 10 before | Expand all | Expand 10 after
3442 self.cli_conn, addr = self.serv.accept() 3634 self.cli_conn, addr = self.serv.accept()
3443 self.addCleanup(self.cli_conn.close) 3635 self.addCleanup(self.cli_conn.close)
3444 cli_thread.join() 3636 cli_thread.join()
3445 self.serv_conn.settimeout(self.timeout) 3637 self.serv_conn.settimeout(self.timeout)
3446 3638
3447 def doConnect(self): 3639 def doConnect(self):
3448 self.serv_conn.connect(self.serv_addr) 3640 self.serv_conn.connect(self.serv_addr)
3449 3641
3450 def checkInterruptedSend(self, func, *args, **kwargs): 3642 def checkInterruptedSend(self, func, *args, **kwargs):
3451 # Check that func(*args, **kwargs), run in a loop, raises 3643 # Check that func(*args, **kwargs), run in a loop, raises
3452 # socket.error with an errno of EINTR when interrupted by a 3644 # OSError with an errno of EINTR when interrupted by a
3453 # signal. 3645 # signal.
3454 with self.assertRaises(socket.error) as cm: 3646 with self.assertRaises(OSError) as cm:
3455 while True: 3647 while True:
3456 self.setAlarm(self.alarm_time) 3648 self.setAlarm(self.alarm_time)
3457 func(*args, **kwargs) 3649 func(*args, **kwargs)
3458 self.assertNotIsInstance(cm.exception, socket.timeout) 3650 self.assertNotIsInstance(cm.exception, socket.timeout)
3459 self.assertEqual(cm.exception.errno, errno.EINTR) 3651 self.assertEqual(cm.exception.errno, errno.EINTR)
3460 3652
3461 # Issue #12958: The following tests have problems on Mac OS X 3653 # Issue #12958: The following tests have problems on OS X prior to 10.7
3462 @support.anticipate_failure(sys.platform == "darwin") 3654 @support.requires_mac_ver(10, 7)
3463 def testInterruptedSendTimeout(self): 3655 def testInterruptedSendTimeout(self):
3464 self.checkInterruptedSend(self.serv_conn.send, b"a"*512) 3656 self.checkInterruptedSend(self.serv_conn.send, b"a"*512)
3465 3657
3466 @support.anticipate_failure(sys.platform == "darwin") 3658 @support.requires_mac_ver(10, 7)
3467 def testInterruptedSendtoTimeout(self): 3659 def testInterruptedSendtoTimeout(self):
3468 # Passing an actual address here as Python's wrapper for 3660 # Passing an actual address here as Python's wrapper for
3469 # sendto() doesn't allow passing a zero-length one; POSIX 3661 # sendto() doesn't allow passing a zero-length one; POSIX
3470 # requires that the address is ignored since the socket is 3662 # requires that the address is ignored since the socket is
3471 # connection-mode, however. 3663 # connection-mode, however.
3472 self.checkInterruptedSend(self.serv_conn.sendto, b"a"*512, 3664 self.checkInterruptedSend(self.serv_conn.sendto, b"a"*512,
3473 self.serv_addr) 3665 self.serv_addr)
3474 3666
3475 @support.anticipate_failure(sys.platform == "darwin") 3667 @support.requires_mac_ver(10, 7)
3476 @requireAttrs(socket.socket, "sendmsg") 3668 @requireAttrs(socket.socket, "sendmsg")
3477 def testInterruptedSendmsgTimeout(self): 3669 def testInterruptedSendmsgTimeout(self):
3478 self.checkInterruptedSend(self.serv_conn.sendmsg, [b"a"*512]) 3670 self.checkInterruptedSend(self.serv_conn.sendmsg, [b"a"*512])
3479 3671
3480 3672
3481 @unittest.skipUnless(thread, 'Threading required for this test.') 3673 @unittest.skipUnless(thread, 'Threading required for this test.')
3482 class TCPCloserTest(ThreadedTCPSocketTest): 3674 class TCPCloserTest(ThreadedTCPSocketTest):
3483 3675
3484 def testClose(self): 3676 def testClose(self):
3485 conn, addr = self.serv.accept() 3677 conn, addr = self.serv.accept()
3486 conn.close() 3678 conn.close()
3487 3679
3488 sd = self.cli 3680 sd = self.cli
3489 read, write, err = select.select([sd], [], [], 1.0) 3681 read, write, err = select.select([sd], [], [], 1.0)
3490 self.assertEqual(read, [sd]) 3682 self.assertEqual(read, [sd])
3491 self.assertEqual(sd.recv(1), b'') 3683 self.assertEqual(sd.recv(1), b'')
3492 3684
3493 # Calling close() many times should be safe. 3685 # Calling close() many times should be safe.
3494 conn.close() 3686 conn.close()
3495 conn.close() 3687 conn.close()
3496 3688
3497 def _testClose(self): 3689 def _testClose(self):
3498 self.cli.connect((HOST, self.port)) 3690 self.cli.connect((HOST, self.port))
3499 time.sleep(1.0) 3691 time.sleep(1.0)
3500 3692
3693 @unittest.skipUnless(hasattr(socket, 'socketpair'),
3694 'test needs socket.socketpair()')
3501 @unittest.skipUnless(thread, 'Threading required for this test.') 3695 @unittest.skipUnless(thread, 'Threading required for this test.')
3502 class BasicSocketPairTest(SocketPairTest): 3696 class BasicSocketPairTest(SocketPairTest):
3503 3697
3504 def __init__(self, methodName='runTest'): 3698 def __init__(self, methodName='runTest'):
3505 SocketPairTest.__init__(self, methodName=methodName) 3699 SocketPairTest.__init__(self, methodName=methodName)
3506 3700
3507 def _check_defaults(self, sock): 3701 def _check_defaults(self, sock):
3508 self.assertIsInstance(sock, socket.socket) 3702 self.assertIsInstance(sock, socket.socket)
3509 if hasattr(socket, 'AF_UNIX'): 3703 if hasattr(socket, 'AF_UNIX'):
3510 self.assertEqual(sock.family, socket.AF_UNIX) 3704 self.assertEqual(sock.family, socket.AF_UNIX)
(...skipping 23 matching lines...) Expand all
3534 self.assertEqual(msg, MSG) 3728 self.assertEqual(msg, MSG)
3535 3729
3536 @unittest.skipUnless(thread, 'Threading required for this test.') 3730 @unittest.skipUnless(thread, 'Threading required for this test.')
3537 class NonBlockingTCPTests(ThreadedTCPSocketTest): 3731 class NonBlockingTCPTests(ThreadedTCPSocketTest):
3538 3732
3539 def __init__(self, methodName='runTest'): 3733 def __init__(self, methodName='runTest'):
3540 ThreadedTCPSocketTest.__init__(self, methodName=methodName) 3734 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
3541 3735
3542 def testSetBlocking(self): 3736 def testSetBlocking(self):
3543 # Testing whether set blocking works 3737 # Testing whether set blocking works
3544 self.serv.setblocking(0) 3738 self.serv.setblocking(True)
3739 self.assertIsNone(self.serv.gettimeout())
3740 self.serv.setblocking(False)
3741 self.assertEqual(self.serv.gettimeout(), 0.0)
3545 start = time.time() 3742 start = time.time()
3546 try: 3743 try:
3547 self.serv.accept() 3744 self.serv.accept()
3548 except socket.error: 3745 except OSError:
3549 pass 3746 pass
3550 end = time.time() 3747 end = time.time()
3551 self.assertLess(end - start, 1.0, "Error setting non-blocking mode.") 3748 self.assertLess(end - start, 1.0, "Error setting non-blocking mode.")
3552 3749
3553 def _testSetBlocking(self): 3750 def _testSetBlocking(self):
3554 pass 3751 pass
3555 3752
3556 if hasattr(socket, "SOCK_NONBLOCK"): 3753 @support.cpython_only
3557 @support.requires_linux_version(2, 6, 28) 3754 def testSetBlocking_overflow(self):
3558 def testInitNonBlocking(self): 3755 # Issue 15989
3559 # reinit server socket 3756 import _testcapi
3560 self.serv.close() 3757 if _testcapi.UINT_MAX >= _testcapi.ULONG_MAX:
3561 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM | 3758 self.skipTest('needs UINT_MAX < ULONG_MAX')
3562 socket.SOCK_NONBLOCK) 3759 self.serv.setblocking(False)
3563 self.port = support.bind_port(self.serv) 3760 self.assertEqual(self.serv.gettimeout(), 0.0)
3564 self.serv.listen(1) 3761 self.serv.setblocking(_testcapi.UINT_MAX + 1)
3565 # actual testing 3762 self.assertIsNone(self.serv.gettimeout())
3566 start = time.time() 3763
3567 try: 3764 _testSetBlocking_overflow = support.cpython_only(_testSetBlocking)
3568 self.serv.accept() 3765
3569 except socket.error: 3766 @unittest.skipUnless(hasattr(socket, 'SOCK_NONBLOCK'),
3570 pass 3767 'test needs socket.SOCK_NONBLOCK')
3571 end = time.time() 3768 @support.requires_linux_version(2, 6, 28)
3572 self.assertLess(end - start, 1.0, "Error creating with non-blocking mode.") 3769 def testInitNonBlocking(self):
3573 3770 # reinit server socket
3574 def _testInitNonBlocking(self): 3771 self.serv.close()
3772 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM |
3773 socket.SOCK_NONBLOCK)
3774 self.port = support.bind_port(self.serv)
3775 self.serv.listen(1)
3776 # actual testing
3777 start = time.time()
3778 try:
3779 self.serv.accept()
3780 except OSError:
3575 pass 3781 pass
3782 end = time.time()
3783 self.assertLess(end - start, 1.0, "Error creating with non-blocking mode .")
3784
3785 def _testInitNonBlocking(self):
3786 pass
3576 3787
3577 def testInheritFlags(self): 3788 def testInheritFlags(self):
3578 # Issue #7995: when calling accept() on a listening socket with a 3789 # Issue #7995: when calling accept() on a listening socket with a
3579 # timeout, the resulting socket should not be non-blocking. 3790 # timeout, the resulting socket should not be non-blocking.
3580 self.serv.settimeout(10) 3791 self.serv.settimeout(10)
3581 try: 3792 try:
3582 conn, addr = self.serv.accept() 3793 conn, addr = self.serv.accept()
3583 message = conn.recv(len(MSG)) 3794 message = conn.recv(len(MSG))
3584 finally: 3795 finally:
3585 conn.close() 3796 conn.close()
3586 self.serv.settimeout(None) 3797 self.serv.settimeout(None)
3587 3798
3588 def _testInheritFlags(self): 3799 def _testInheritFlags(self):
3589 time.sleep(0.1) 3800 time.sleep(0.1)
3590 self.cli.connect((HOST, self.port)) 3801 self.cli.connect((HOST, self.port))
3591 time.sleep(0.5) 3802 time.sleep(0.5)
3592 self.cli.send(MSG) 3803 self.cli.send(MSG)
3593 3804
3594 def testAccept(self): 3805 def testAccept(self):
3595 # Testing non-blocking accept 3806 # Testing non-blocking accept
3596 self.serv.setblocking(0) 3807 self.serv.setblocking(0)
3597 try: 3808 try:
3598 conn, addr = self.serv.accept() 3809 conn, addr = self.serv.accept()
3599 except socket.error: 3810 except OSError:
3600 pass 3811 pass
3601 else: 3812 else:
3602 self.fail("Error trying to do non-blocking accept.") 3813 self.fail("Error trying to do non-blocking accept.")
3603 read, write, err = select.select([self.serv], [], []) 3814 read, write, err = select.select([self.serv], [], [])
3604 if self.serv in read: 3815 if self.serv in read:
3605 conn, addr = self.serv.accept() 3816 conn, addr = self.serv.accept()
3606 conn.close() 3817 conn.close()
3607 else: 3818 else:
3608 self.fail("Error trying to do accept after select.") 3819 self.fail("Error trying to do accept after select.")
3609 3820
3610 def _testAccept(self): 3821 def _testAccept(self):
3611 time.sleep(0.1) 3822 time.sleep(0.1)
3612 self.cli.connect((HOST, self.port)) 3823 self.cli.connect((HOST, self.port))
3613 3824
3614 def testConnect(self): 3825 def testConnect(self):
3615 # Testing non-blocking connect 3826 # Testing non-blocking connect
3616 conn, addr = self.serv.accept() 3827 conn, addr = self.serv.accept()
3617 conn.close() 3828 conn.close()
3618 3829
3619 def _testConnect(self): 3830 def _testConnect(self):
3620 self.cli.settimeout(10) 3831 self.cli.settimeout(10)
3621 self.cli.connect((HOST, self.port)) 3832 self.cli.connect((HOST, self.port))
3622 3833
3623 def testRecv(self): 3834 def testRecv(self):
3624 # Testing non-blocking recv 3835 # Testing non-blocking recv
3625 conn, addr = self.serv.accept() 3836 conn, addr = self.serv.accept()
3626 conn.setblocking(0) 3837 conn.setblocking(0)
3627 try: 3838 try:
3628 msg = conn.recv(len(MSG)) 3839 msg = conn.recv(len(MSG))
3629 except socket.error: 3840 except OSError:
3630 pass 3841 pass
3631 else: 3842 else:
3632 self.fail("Error trying to do non-blocking recv.") 3843 self.fail("Error trying to do non-blocking recv.")
3633 read, write, err = select.select([conn], [], []) 3844 read, write, err = select.select([conn], [], [])
3634 if conn in read: 3845 if conn in read:
3635 msg = conn.recv(len(MSG)) 3846 msg = conn.recv(len(MSG))
3636 conn.close() 3847 conn.close()
3637 self.assertEqual(msg, MSG) 3848 self.assertEqual(msg, MSG)
3638 else: 3849 else:
3639 self.fail("Error during select call to non-blocking socket.") 3850 self.fail("Error during select call to non-blocking socket.")
(...skipping 62 matching lines...) Expand 10 before | Expand all | Expand 10 after
3702 SocketConnectedTest.clientTearDown(self) 3913 SocketConnectedTest.clientTearDown(self)
3703 3914
3704 def testReadAfterTimeout(self): 3915 def testReadAfterTimeout(self):
3705 # Issue #7322: A file object must disallow further reads 3916 # Issue #7322: A file object must disallow further reads
3706 # after a timeout has occurred. 3917 # after a timeout has occurred.
3707 self.cli_conn.settimeout(1) 3918 self.cli_conn.settimeout(1)
3708 self.read_file.read(3) 3919 self.read_file.read(3)
3709 # First read raises a timeout 3920 # First read raises a timeout
3710 self.assertRaises(socket.timeout, self.read_file.read, 1) 3921 self.assertRaises(socket.timeout, self.read_file.read, 1)
3711 # Second read is disallowed 3922 # Second read is disallowed
3712 with self.assertRaises(IOError) as ctx: 3923 with self.assertRaises(OSError) as ctx:
3713 self.read_file.read(1) 3924 self.read_file.read(1)
3714 self.assertIn("cannot read from timed out object", str(ctx.exception)) 3925 self.assertIn("cannot read from timed out object", str(ctx.exception))
3715 3926
3716 def _testReadAfterTimeout(self): 3927 def _testReadAfterTimeout(self):
3717 self.write_file.write(self.write_msg[0:3]) 3928 self.write_file.write(self.write_msg[0:3])
3718 self.write_file.flush() 3929 self.write_file.flush()
3719 self.serv_finished.wait() 3930 self.serv_finished.wait()
3720 3931
3721 def testSmallRead(self): 3932 def testSmallRead(self):
3722 # Performing small file read test 3933 # Performing small file read test
(...skipping 54 matching lines...) Expand 10 before | Expand all | Expand 10 after
3777 msg = self.cli_conn.recv(len(MSG)) 3988 msg = self.cli_conn.recv(len(MSG))
3778 if isinstance(self.read_msg, str): 3989 if isinstance(self.read_msg, str):
3779 msg = msg.decode() 3990 msg = msg.decode()
3780 self.assertEqual(msg, self.read_msg) 3991 self.assertEqual(msg, self.read_msg)
3781 3992
3782 def _testMakefileAfterMakefileClose(self): 3993 def _testMakefileAfterMakefileClose(self):
3783 self.write_file.write(self.write_msg) 3994 self.write_file.write(self.write_msg)
3784 self.write_file.flush() 3995 self.write_file.flush()
3785 3996
3786 def testClosedAttr(self): 3997 def testClosedAttr(self):
3787 self.assertFalse(self.read_file.closed) 3998 self.assertTrue(not self.read_file.closed)
3788 3999
3789 def _testClosedAttr(self): 4000 def _testClosedAttr(self):
3790 self.assertFalse(self.write_file.closed) 4001 self.assertTrue(not self.write_file.closed)
3791 4002
3792 def testAttributes(self): 4003 def testAttributes(self):
3793 self.assertEqual(self.read_file.mode, self.read_mode) 4004 self.assertEqual(self.read_file.mode, self.read_mode)
3794 self.assertEqual(self.read_file.name, self.cli_conn.fileno()) 4005 self.assertEqual(self.read_file.name, self.cli_conn.fileno())
3795 4006
3796 def _testAttributes(self): 4007 def _testAttributes(self):
3797 self.assertEqual(self.write_file.mode, self.write_mode) 4008 self.assertEqual(self.write_file.mode, self.write_mode)
3798 self.assertEqual(self.write_file.name, self.serv_conn.fileno()) 4009 self.assertEqual(self.write_file.name, self.serv_conn.fileno())
3799 4010
3800 def testRealClose(self): 4011 def testRealClose(self):
3801 self.read_file.close() 4012 self.read_file.close()
3802 self.assertRaises(ValueError, self.read_file.fileno) 4013 self.assertRaises(ValueError, self.read_file.fileno)
3803 self.cli_conn.close() 4014 self.cli_conn.close()
3804 self.assertRaises(socket.error, self.cli_conn.getsockname) 4015 self.assertRaises(OSError, self.cli_conn.getsockname)
3805 4016
3806 def _testRealClose(self): 4017 def _testRealClose(self):
3807 pass 4018 pass
3808 4019
3809 4020
3810 class FileObjectInterruptedTestCase(unittest.TestCase): 4021 class FileObjectInterruptedTestCase(unittest.TestCase):
3811 """Test that the file object correctly handles EINTR internally.""" 4022 """Test that the file object correctly handles EINTR internally."""
3812 4023
3813 class MockSocket(object): 4024 class MockSocket(object):
3814 def __init__(self, recv_funcs=()): 4025 def __init__(self, recv_funcs=()):
(...skipping 16 matching lines...) Expand all
3831 buffering = io.DEFAULT_BUFFER_SIZE 4042 buffering = io.DEFAULT_BUFFER_SIZE
3832 if buffering == 0: 4043 if buffering == 0:
3833 return raw 4044 return raw
3834 buffer = io.BufferedReader(raw, buffering) 4045 buffer = io.BufferedReader(raw, buffering)
3835 text = io.TextIOWrapper(buffer, None, None) 4046 text = io.TextIOWrapper(buffer, None, None)
3836 text.mode = "rb" 4047 text.mode = "rb"
3837 return text 4048 return text
3838 4049
3839 @staticmethod 4050 @staticmethod
3840 def _raise_eintr(): 4051 def _raise_eintr():
3841 raise socket.error(errno.EINTR, "interrupted") 4052 raise OSError(errno.EINTR, "interrupted")
3842 4053
3843 def _textiowrap_mock_socket(self, mock, buffering=-1): 4054 def _textiowrap_mock_socket(self, mock, buffering=-1):
3844 raw = socket.SocketIO(mock, "r") 4055 raw = socket.SocketIO(mock, "r")
3845 if buffering < 0: 4056 if buffering < 0:
3846 buffering = io.DEFAULT_BUFFER_SIZE 4057 buffering = io.DEFAULT_BUFFER_SIZE
3847 if buffering == 0: 4058 if buffering == 0:
3848 return raw 4059 return raw
3849 buffer = io.BufferedReader(raw, buffering) 4060 buffer = io.BufferedReader(raw, buffering)
3850 text = io.TextIOWrapper(buffer, None, None) 4061 text = io.TextIOWrapper(buffer, None, None)
3851 text.mode = "rb" 4062 text.mode = "rb"
(...skipping 91 matching lines...) Expand 10 before | Expand all | Expand 10 after
3943 self.write_file.write(b"B. " + self.write_msg) 4154 self.write_file.write(b"B. " + self.write_msg)
3944 self.write_file.flush() 4155 self.write_file.flush()
3945 4156
3946 def testMakefileClose(self): 4157 def testMakefileClose(self):
3947 # The file returned by makefile should keep the socket open... 4158 # The file returned by makefile should keep the socket open...
3948 self.cli_conn.close() 4159 self.cli_conn.close()
3949 msg = self.cli_conn.recv(1024) 4160 msg = self.cli_conn.recv(1024)
3950 self.assertEqual(msg, self.read_msg) 4161 self.assertEqual(msg, self.read_msg)
3951 # ...until the file is itself closed 4162 # ...until the file is itself closed
3952 self.read_file.close() 4163 self.read_file.close()
3953 self.assertRaises(socket.error, self.cli_conn.recv, 1024) 4164 self.assertRaises(OSError, self.cli_conn.recv, 1024)
3954 4165
3955 def _testMakefileClose(self): 4166 def _testMakefileClose(self):
3956 self.write_file.write(self.write_msg) 4167 self.write_file.write(self.write_msg)
3957 self.write_file.flush() 4168 self.write_file.flush()
3958 4169
3959 def testMakefileCloseSocketDestroy(self): 4170 def testMakefileCloseSocketDestroy(self):
3960 refcount_before = sys.getrefcount(self.cli_conn) 4171 refcount_before = sys.getrefcount(self.cli_conn)
3961 self.read_file.close() 4172 self.read_file.close()
3962 refcount_after = sys.getrefcount(self.cli_conn) 4173 refcount_after = sys.getrefcount(self.cli_conn)
3963 self.assertEqual(refcount_before - 1, refcount_after) 4174 self.assertEqual(refcount_before - 1, refcount_after)
(...skipping 37 matching lines...) Expand 10 before | Expand all | Expand 10 after
4001 self.cli_finished.wait(5.0) 4212 self.cli_finished.wait(5.0)
4002 # The client thread can't skip directly - the SkipTest exception 4213 # The client thread can't skip directly - the SkipTest exception
4003 # would appear as a failure. 4214 # would appear as a failure.
4004 if self.serv_skipped: 4215 if self.serv_skipped:
4005 self.skipTest(self.serv_skipped) 4216 self.skipTest(self.serv_skipped)
4006 4217
4007 def _testWriteNonBlocking(self): 4218 def _testWriteNonBlocking(self):
4008 self.serv_skipped = None 4219 self.serv_skipped = None
4009 self.serv_conn.setblocking(False) 4220 self.serv_conn.setblocking(False)
4010 # Try to saturate the socket buffer pipe with repeated large writes. 4221 # Try to saturate the socket buffer pipe with repeated large writes.
4011 BIG = b"x" * (1024 ** 2) 4222 BIG = b"x" * support.SOCK_MAX_SIZE
4012 LIMIT = 10 4223 LIMIT = 10
4013 # The first write() succeeds since a chunk of data can be buffered 4224 # The first write() succeeds since a chunk of data can be buffered
4014 n = self.write_file.write(BIG) 4225 n = self.write_file.write(BIG)
4015 self.assertGreater(n, 0) 4226 self.assertGreater(n, 0)
4016 for i in range(LIMIT): 4227 for i in range(LIMIT):
4017 n = self.write_file.write(BIG) 4228 n = self.write_file.write(BIG)
4018 if n is None: 4229 if n is None:
4019 # Succeeded 4230 # Succeeded
4020 break 4231 break
4021 self.assertGreater(n, 0) 4232 self.assertGreater(n, 0)
(...skipping 70 matching lines...) Expand 10 before | Expand all | Expand 10 after
4092 socket.socket = self.MockSocket 4303 socket.socket = self.MockSocket
4093 try: 4304 try:
4094 yield 4305 yield
4095 finally: 4306 finally:
4096 socket.socket = old_socket 4307 socket.socket = old_socket
4097 4308
4098 def test_connect(self): 4309 def test_connect(self):
4099 port = support.find_unused_port() 4310 port = support.find_unused_port()
4100 cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 4311 cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
4101 self.addCleanup(cli.close) 4312 self.addCleanup(cli.close)
4102 with self.assertRaises(socket.error) as cm: 4313 with self.assertRaises(OSError) as cm:
4103 cli.connect((HOST, port)) 4314 cli.connect((HOST, port))
4104 self.assertEqual(cm.exception.errno, errno.ECONNREFUSED) 4315 self.assertEqual(cm.exception.errno, errno.ECONNREFUSED)
4105 4316
4106 def test_create_connection(self): 4317 def test_create_connection(self):
4107 # Issue #9792: errors raised by create_connection() should have 4318 # Issue #9792: errors raised by create_connection() should have
4108 # a proper errno attribute. 4319 # a proper errno attribute.
4109 port = support.find_unused_port() 4320 port = support.find_unused_port()
4110 with self.assertRaises(socket.error) as cm: 4321 with self.assertRaises(OSError) as cm:
4111 socket.create_connection((HOST, port)) 4322 socket.create_connection((HOST, port))
4112 4323
4113 # Issue #16257: create_connection() calls getaddrinfo() against 4324 # Issue #16257: create_connection() calls getaddrinfo() against
4114 # 'localhost'. This may result in an IPV6 addr being returned 4325 # 'localhost'. This may result in an IPV6 addr being returned
4115 # as well as an IPV4 one: 4326 # as well as an IPV4 one:
4116 # >>> socket.getaddrinfo('localhost', port, 0, SOCK_STREAM) 4327 # >>> socket.getaddrinfo('localhost', port, 0, SOCK_STREAM)
4117 # >>> [(2, 2, 0, '', ('127.0.0.1', 41230)), 4328 # >>> [(2, 2, 0, '', ('127.0.0.1', 41230)),
4118 # (26, 2, 0, '', ('::1', 41230, 0, 0))] 4329 # (26, 2, 0, '', ('::1', 41230, 0, 0))]
4119 # 4330 #
4120 # create_connection() enumerates through all the addresses returned 4331 # create_connection() enumerates through all the addresses returned
(...skipping 127 matching lines...) Expand 10 before | Expand all | Expand 10 after
4248 self.assertRaises(socket.timeout, raise_timeout, 4459 self.assertRaises(socket.timeout, raise_timeout,
4249 "Error generating a timeout exception (TCP)") 4460 "Error generating a timeout exception (TCP)")
4250 4461
4251 def testTimeoutZero(self): 4462 def testTimeoutZero(self):
4252 ok = False 4463 ok = False
4253 try: 4464 try:
4254 self.serv.settimeout(0.0) 4465 self.serv.settimeout(0.0)
4255 foo = self.serv.accept() 4466 foo = self.serv.accept()
4256 except socket.timeout: 4467 except socket.timeout:
4257 self.fail("caught timeout instead of error (TCP)") 4468 self.fail("caught timeout instead of error (TCP)")
4258 except socket.error: 4469 except OSError:
4259 ok = True 4470 ok = True
4260 except: 4471 except:
4261 self.fail("caught unexpected exception (TCP)") 4472 self.fail("caught unexpected exception (TCP)")
4262 if not ok: 4473 if not ok:
4263 self.fail("accept() returned success when we did not expect it") 4474 self.fail("accept() returned success when we did not expect it")
4264 4475
4476 @unittest.skipUnless(hasattr(signal, 'alarm'),
4477 'test needs signal.alarm()')
4265 def testInterruptedTimeout(self): 4478 def testInterruptedTimeout(self):
4266 # XXX I don't know how to do this test on MSWindows or any other 4479 # XXX I don't know how to do this test on MSWindows or any other
4267 # plaform that doesn't support signal.alarm() or os.kill(), though 4480 # plaform that doesn't support signal.alarm() or os.kill(), though
4268 # the bug should have existed on all platforms. 4481 # the bug should have existed on all platforms.
4269 if not hasattr(signal, "alarm"):
4270 return # can only test on *nix
4271 self.serv.settimeout(5.0) # must be longer than alarm 4482 self.serv.settimeout(5.0) # must be longer than alarm
4272 class Alarm(Exception): 4483 class Alarm(Exception):
4273 pass 4484 pass
4274 def alarm_handler(signal, frame): 4485 def alarm_handler(signal, frame):
4275 raise Alarm 4486 raise Alarm
4276 old_alarm = signal.signal(signal.SIGALRM, alarm_handler) 4487 old_alarm = signal.signal(signal.SIGALRM, alarm_handler)
4277 try: 4488 try:
4278 signal.alarm(2) # POSIX allows alarm to be up to 1 second early 4489 signal.alarm(2) # POSIX allows alarm to be up to 1 second early
4279 try: 4490 try:
4280 foo = self.serv.accept() 4491 foo = self.serv.accept()
(...skipping 24 matching lines...) Expand all
4305 self.assertRaises(socket.timeout, raise_timeout, 4516 self.assertRaises(socket.timeout, raise_timeout,
4306 "Error generating a timeout exception (UDP)") 4517 "Error generating a timeout exception (UDP)")
4307 4518
4308 def testTimeoutZero(self): 4519 def testTimeoutZero(self):
4309 ok = False 4520 ok = False
4310 try: 4521 try:
4311 self.serv.settimeout(0.0) 4522 self.serv.settimeout(0.0)
4312 foo = self.serv.recv(1024) 4523 foo = self.serv.recv(1024)
4313 except socket.timeout: 4524 except socket.timeout:
4314 self.fail("caught timeout instead of error (UDP)") 4525 self.fail("caught timeout instead of error (UDP)")
4315 except socket.error: 4526 except OSError:
4316 ok = True 4527 ok = True
4317 except: 4528 except:
4318 self.fail("caught unexpected exception (UDP)") 4529 self.fail("caught unexpected exception (UDP)")
4319 if not ok: 4530 if not ok:
4320 self.fail("recv() returned success when we did not expect it") 4531 self.fail("recv() returned success when we did not expect it")
4321 4532
4322 class TestExceptions(unittest.TestCase): 4533 class TestExceptions(unittest.TestCase):
4323 4534
4324 def testExceptionTree(self): 4535 def testExceptionTree(self):
4325 self.assertTrue(issubclass(socket.error, Exception)) 4536 self.assertTrue(issubclass(OSError, Exception))
4326 self.assertTrue(issubclass(socket.herror, socket.error)) 4537 self.assertTrue(issubclass(socket.herror, OSError))
4327 self.assertTrue(issubclass(socket.gaierror, socket.error)) 4538 self.assertTrue(issubclass(socket.gaierror, OSError))
4328 self.assertTrue(issubclass(socket.timeout, socket.error)) 4539 self.assertTrue(issubclass(socket.timeout, OSError))
4329 4540
4541 @unittest.skipUnless(sys.platform == 'linux', 'Linux specific test')
4330 class TestLinuxAbstractNamespace(unittest.TestCase): 4542 class TestLinuxAbstractNamespace(unittest.TestCase):
4331 4543
4332 UNIX_PATH_MAX = 108 4544 UNIX_PATH_MAX = 108
4333 4545
4334 def testLinuxAbstractNamespace(self): 4546 def testLinuxAbstractNamespace(self):
4335 address = b"\x00python-test-hello\x00\xff" 4547 address = b"\x00python-test-hello\x00\xff"
4336 with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s1: 4548 with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s1:
4337 s1.bind(address) 4549 s1.bind(address)
4338 s1.listen(1) 4550 s1.listen(1)
4339 with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s2: 4551 with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s2:
4340 s2.connect(s1.getsockname()) 4552 s2.connect(s1.getsockname())
4341 with s1.accept()[0] as s3: 4553 with s1.accept()[0] as s3:
4342 self.assertEqual(s1.getsockname(), address) 4554 self.assertEqual(s1.getsockname(), address)
4343 self.assertEqual(s2.getpeername(), address) 4555 self.assertEqual(s2.getpeername(), address)
4344 4556
4345 def testMaxName(self): 4557 def testMaxName(self):
4346 address = b"\x00" + b"h" * (self.UNIX_PATH_MAX - 1) 4558 address = b"\x00" + b"h" * (self.UNIX_PATH_MAX - 1)
4347 with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s: 4559 with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
4348 s.bind(address) 4560 s.bind(address)
4349 self.assertEqual(s.getsockname(), address) 4561 self.assertEqual(s.getsockname(), address)
4350 4562
4351 def testNameOverflow(self): 4563 def testNameOverflow(self):
4352 address = "\x00" + "h" * self.UNIX_PATH_MAX 4564 address = "\x00" + "h" * self.UNIX_PATH_MAX
4353 with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s: 4565 with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
4354 self.assertRaises(socket.error, s.bind, address) 4566 self.assertRaises(OSError, s.bind, address)
4355 4567
4356 def testStrName(self): 4568 def testStrName(self):
4357 # Check that an abstract name can be passed as a string. 4569 # Check that an abstract name can be passed as a string.
4358 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) 4570 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
4359 try: 4571 try:
4360 s.bind("\x00python\x00test\x00") 4572 s.bind("\x00python\x00test\x00")
4361 self.assertEqual(s.getsockname(), b"\x00python\x00test\x00") 4573 self.assertEqual(s.getsockname(), b"\x00python\x00test\x00")
4362 finally: 4574 finally:
4363 s.close() 4575 s.close()
4364 4576
4577 @unittest.skipUnless(hasattr(socket, 'AF_UNIX'), 'test needs socket.AF_UNIX')
4365 class TestUnixDomain(unittest.TestCase): 4578 class TestUnixDomain(unittest.TestCase):
4366 4579
4367 def setUp(self): 4580 def setUp(self):
4368 self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) 4581 self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
4369 4582
4370 def tearDown(self): 4583 def tearDown(self):
4371 self.sock.close() 4584 self.sock.close()
4372 4585
4373 def encoded(self, path): 4586 def encoded(self, path):
4374 # Return the given path encoded in the file system encoding, 4587 # Return the given path encoded in the file system encoding,
(...skipping 110 matching lines...) Expand 10 before | Expand all | Expand 10 after
4485 4698
4486 def testRecvFromIntoMemoryview(self): 4699 def testRecvFromIntoMemoryview(self):
4487 buf = bytearray(1024) 4700 buf = bytearray(1024)
4488 nbytes, addr = self.cli_conn.recvfrom_into(memoryview(buf)) 4701 nbytes, addr = self.cli_conn.recvfrom_into(memoryview(buf))
4489 self.assertEqual(nbytes, len(MSG)) 4702 self.assertEqual(nbytes, len(MSG))
4490 msg = buf[:len(MSG)] 4703 msg = buf[:len(MSG)]
4491 self.assertEqual(msg, MSG) 4704 self.assertEqual(msg, MSG)
4492 4705
4493 _testRecvFromIntoMemoryview = _testRecvFromIntoArray 4706 _testRecvFromIntoMemoryview = _testRecvFromIntoArray
4494 4707
4708 def testRecvFromIntoSmallBuffer(self):
4709 # See issue #20246.
4710 buf = bytearray(8)
4711 self.assertRaises(ValueError, self.cli_conn.recvfrom_into, buf, 1024)
4712
4713 def _testRecvFromIntoSmallBuffer(self):
4714 self.serv_conn.send(MSG)
4715
4716 def testRecvFromIntoEmptyBuffer(self):
4717 buf = bytearray()
4718 self.cli_conn.recvfrom_into(buf)
4719 self.cli_conn.recvfrom_into(buf, 0)
4720
4721 _testRecvFromIntoEmptyBuffer = _testRecvFromIntoArray
4722
4495 4723
4496 TIPC_STYPE = 2000 4724 TIPC_STYPE = 2000
4497 TIPC_LOWER = 200 4725 TIPC_LOWER = 200
4498 TIPC_UPPER = 210 4726 TIPC_UPPER = 210
4499 4727
4500 def isTipcAvailable(): 4728 def isTipcAvailable():
4501 """Check if the TIPC module is loaded 4729 """Check if the TIPC module is loaded
4502 4730
4503 The TIPC module is not loaded automatically on Ubuntu and probably 4731 The TIPC module is not loaded automatically on Ubuntu and probably
4504 other Linux distros. 4732 other Linux distros.
4505 """ 4733 """
4506 if not hasattr(socket, "AF_TIPC"): 4734 if not hasattr(socket, "AF_TIPC"):
4507 return False 4735 return False
4508 if not os.path.isfile("/proc/modules"): 4736 if not os.path.isfile("/proc/modules"):
4509 return False 4737 return False
4510 with open("/proc/modules") as f: 4738 with open("/proc/modules") as f:
4511 for line in f: 4739 for line in f:
4512 if line.startswith("tipc "): 4740 if line.startswith("tipc "):
4513 return True 4741 return True
4514 if support.verbose:
4515 print("TIPC module is not loaded, please 'sudo modprobe tipc'")
4516 return False 4742 return False
4517 4743
4744 @unittest.skipUnless(isTipcAvailable(),
4745 "TIPC module is not loaded, please 'sudo modprobe tipc'")
4518 class TIPCTest(unittest.TestCase): 4746 class TIPCTest(unittest.TestCase):
4519 def testRDM(self): 4747 def testRDM(self):
4520 srv = socket.socket(socket.AF_TIPC, socket.SOCK_RDM) 4748 srv = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
4521 cli = socket.socket(socket.AF_TIPC, socket.SOCK_RDM) 4749 cli = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
4522 self.addCleanup(srv.close) 4750 self.addCleanup(srv.close)
4523 self.addCleanup(cli.close) 4751 self.addCleanup(cli.close)
4524 4752
4525 srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 4753 srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
4526 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE, 4754 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
4527 TIPC_LOWER, TIPC_UPPER) 4755 TIPC_LOWER, TIPC_UPPER)
4528 srv.bind(srvaddr) 4756 srv.bind(srvaddr)
4529 4757
4530 sendaddr = (socket.TIPC_ADDR_NAME, TIPC_STYPE, 4758 sendaddr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
4531 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0) 4759 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
4532 cli.sendto(MSG, sendaddr) 4760 cli.sendto(MSG, sendaddr)
4533 4761
4534 msg, recvaddr = srv.recvfrom(1024) 4762 msg, recvaddr = srv.recvfrom(1024)
4535 4763
4536 self.assertEqual(cli.getsockname(), recvaddr) 4764 self.assertEqual(cli.getsockname(), recvaddr)
4537 self.assertEqual(msg, MSG) 4765 self.assertEqual(msg, MSG)
4538 4766
4539 4767
4768 @unittest.skipUnless(isTipcAvailable(),
4769 "TIPC module is not loaded, please 'sudo modprobe tipc'")
4540 class TIPCThreadableTest(unittest.TestCase, ThreadableTest): 4770 class TIPCThreadableTest(unittest.TestCase, ThreadableTest):
4541 def __init__(self, methodName = 'runTest'): 4771 def __init__(self, methodName = 'runTest'):
4542 unittest.TestCase.__init__(self, methodName = methodName) 4772 unittest.TestCase.__init__(self, methodName = methodName)
4543 ThreadableTest.__init__(self) 4773 ThreadableTest.__init__(self)
4544 4774
4545 def setUp(self): 4775 def setUp(self):
4546 self.srv = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM) 4776 self.srv = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
4547 self.addCleanup(self.srv.close) 4777 self.addCleanup(self.srv.close)
4548 self.srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 4778 self.srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
4549 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE, 4779 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
(...skipping 33 matching lines...) Expand 10 before | Expand all | Expand 10 after
4583 # base test 4813 # base test
4584 with socket.socket() as sock: 4814 with socket.socket() as sock:
4585 self.assertFalse(sock._closed) 4815 self.assertFalse(sock._closed)
4586 self.assertTrue(sock._closed) 4816 self.assertTrue(sock._closed)
4587 # close inside with block 4817 # close inside with block
4588 with socket.socket() as sock: 4818 with socket.socket() as sock:
4589 sock.close() 4819 sock.close()
4590 self.assertTrue(sock._closed) 4820 self.assertTrue(sock._closed)
4591 # exception inside with block 4821 # exception inside with block
4592 with socket.socket() as sock: 4822 with socket.socket() as sock:
4593 self.assertRaises(socket.error, sock.sendall, b'foo') 4823 self.assertRaises(OSError, sock.sendall, b'foo')
4594 self.assertTrue(sock._closed) 4824 self.assertTrue(sock._closed)
4595 4825
4596 def testCreateConnectionBase(self): 4826 def testCreateConnectionBase(self):
4597 conn, addr = self.serv.accept() 4827 conn, addr = self.serv.accept()
4598 self.addCleanup(conn.close) 4828 self.addCleanup(conn.close)
4599 data = conn.recv(1024) 4829 data = conn.recv(1024)
4600 conn.sendall(data) 4830 conn.sendall(data)
4601 4831
4602 def _testCreateConnectionBase(self): 4832 def _testCreateConnectionBase(self):
4603 address = self.serv.getsockname() 4833 address = self.serv.getsockname()
4604 with socket.create_connection(address) as sock: 4834 with socket.create_connection(address) as sock:
4605 self.assertFalse(sock._closed) 4835 self.assertFalse(sock._closed)
4606 sock.sendall(b'foo') 4836 sock.sendall(b'foo')
4607 self.assertEqual(sock.recv(1024), b'foo') 4837 self.assertEqual(sock.recv(1024), b'foo')
4608 self.assertTrue(sock._closed) 4838 self.assertTrue(sock._closed)
4609 4839
4610 def testCreateConnectionClose(self): 4840 def testCreateConnectionClose(self):
4611 conn, addr = self.serv.accept() 4841 conn, addr = self.serv.accept()
4612 self.addCleanup(conn.close) 4842 self.addCleanup(conn.close)
4613 data = conn.recv(1024) 4843 data = conn.recv(1024)
4614 conn.sendall(data) 4844 conn.sendall(data)
4615 4845
4616 def _testCreateConnectionClose(self): 4846 def _testCreateConnectionClose(self):
4617 address = self.serv.getsockname() 4847 address = self.serv.getsockname()
4618 with socket.create_connection(address) as sock: 4848 with socket.create_connection(address) as sock:
4619 sock.close() 4849 sock.close()
4620 self.assertTrue(sock._closed) 4850 self.assertTrue(sock._closed)
4621 self.assertRaises(socket.error, sock.sendall, b'foo') 4851 self.assertRaises(OSError, sock.sendall, b'foo')
4622 4852
4623 4853
4624 @unittest.skipUnless(hasattr(socket, "SOCK_CLOEXEC"), 4854 class InheritanceTest(unittest.TestCase):
4625 "SOCK_CLOEXEC not defined") 4855 @unittest.skipUnless(hasattr(socket, "SOCK_CLOEXEC"),
4626 @unittest.skipUnless(fcntl, "module fcntl not available") 4856 "SOCK_CLOEXEC not defined")
4627 class CloexecConstantTest(unittest.TestCase):
4628 @support.requires_linux_version(2, 6, 28) 4857 @support.requires_linux_version(2, 6, 28)
4629 def test_SOCK_CLOEXEC(self): 4858 def test_SOCK_CLOEXEC(self):
4630 with socket.socket(socket.AF_INET, 4859 with socket.socket(socket.AF_INET,
4631 socket.SOCK_STREAM | socket.SOCK_CLOEXEC) as s: 4860 socket.SOCK_STREAM | socket.SOCK_CLOEXEC) as s:
4632 self.assertTrue(s.type & socket.SOCK_CLOEXEC) 4861 self.assertTrue(s.type & socket.SOCK_CLOEXEC)
4633 self.assertTrue(fcntl.fcntl(s, fcntl.F_GETFD) & fcntl.FD_CLOEXEC) 4862 self.assertFalse(s.get_inheritable())
4863
4864 def test_default_inheritable(self):
4865 sock = socket.socket()
4866 with sock:
4867 self.assertEqual(sock.get_inheritable(), False)
4868
4869 def test_dup(self):
4870 sock = socket.socket()
4871 with sock:
4872 newsock = sock.dup()
4873 sock.close()
4874 with newsock:
4875 self.assertEqual(newsock.get_inheritable(), False)
4876
4877 def test_set_inheritable(self):
4878 sock = socket.socket()
4879 with sock:
4880 sock.set_inheritable(True)
4881 self.assertEqual(sock.get_inheritable(), True)
4882
4883 sock.set_inheritable(False)
4884 self.assertEqual(sock.get_inheritable(), False)
4885
4886 @unittest.skipIf(fcntl is None, "need fcntl")
4887 def test_get_inheritable_cloexec(self):
4888 sock = socket.socket()
4889 with sock:
4890 fd = sock.fileno()
4891 self.assertEqual(sock.get_inheritable(), False)
4892
4893 # clear FD_CLOEXEC flag
4894 flags = fcntl.fcntl(fd, fcntl.F_GETFD)
4895 flags &= ~fcntl.FD_CLOEXEC
4896 fcntl.fcntl(fd, fcntl.F_SETFD, flags)
4897
4898 self.assertEqual(sock.get_inheritable(), True)
4899
4900 @unittest.skipIf(fcntl is None, "need fcntl")
4901 def test_set_inheritable_cloexec(self):
4902 sock = socket.socket()
4903 with sock:
4904 fd = sock.fileno()
4905 self.assertEqual(fcntl.fcntl(fd, fcntl.F_GETFD) & fcntl.FD_CLOEXEC,
4906 fcntl.FD_CLOEXEC)
4907
4908 sock.set_inheritable(True)
4909 self.assertEqual(fcntl.fcntl(fd, fcntl.F_GETFD) & fcntl.FD_CLOEXEC,
4910 0)
4911
4912
4913 @unittest.skipUnless(hasattr(socket, "socketpair"),
4914 "need socket.socketpair()")
4915 def test_socketpair(self):
4916 s1, s2 = socket.socketpair()
4917 self.addCleanup(s1.close)
4918 self.addCleanup(s2.close)
4919 self.assertEqual(s1.get_inheritable(), False)
4920 self.assertEqual(s2.get_inheritable(), False)
4634 4921
4635 4922
4636 @unittest.skipUnless(hasattr(socket, "SOCK_NONBLOCK"), 4923 @unittest.skipUnless(hasattr(socket, "SOCK_NONBLOCK"),
4637 "SOCK_NONBLOCK not defined") 4924 "SOCK_NONBLOCK not defined")
4638 class NonblockConstantTest(unittest.TestCase): 4925 class NonblockConstantTest(unittest.TestCase):
4639 def checkNonblock(self, s, nonblock=True, timeout=0.0): 4926 def checkNonblock(self, s, nonblock=True, timeout=0.0):
4640 if nonblock: 4927 if nonblock:
4641 self.assertTrue(s.type & socket.SOCK_NONBLOCK) 4928 self.assertTrue(s.type & socket.SOCK_NONBLOCK)
4642 self.assertEqual(s.gettimeout(), timeout) 4929 self.assertEqual(s.gettimeout(), timeout)
4643 else: 4930 else:
(...skipping 148 matching lines...) Expand 10 before | Expand all | Expand 10 after
4792 UnbufferedFileObjectClassTestCase, 5079 UnbufferedFileObjectClassTestCase,
4793 LineBufferedFileObjectClassTestCase, 5080 LineBufferedFileObjectClassTestCase,
4794 SmallBufferedFileObjectClassTestCase, 5081 SmallBufferedFileObjectClassTestCase,
4795 UnicodeReadFileObjectClassTestCase, 5082 UnicodeReadFileObjectClassTestCase,
4796 UnicodeWriteFileObjectClassTestCase, 5083 UnicodeWriteFileObjectClassTestCase,
4797 UnicodeReadWriteFileObjectClassTestCase, 5084 UnicodeReadWriteFileObjectClassTestCase,
4798 NetworkConnectionNoServer, 5085 NetworkConnectionNoServer,
4799 NetworkConnectionAttributesTest, 5086 NetworkConnectionAttributesTest,
4800 NetworkConnectionBehaviourTest, 5087 NetworkConnectionBehaviourTest,
4801 ContextManagersTest, 5088 ContextManagersTest,
4802 CloexecConstantTest, 5089 InheritanceTest,
4803 NonblockConstantTest 5090 NonblockConstantTest
4804 ]) 5091 ])
4805 if hasattr(socket, "socketpair"): 5092 tests.append(BasicSocketPairTest)
4806 tests.append(BasicSocketPairTest) 5093 tests.append(TestUnixDomain)
4807 if hasattr(socket, "AF_UNIX"): 5094 tests.append(TestLinuxAbstractNamespace)
4808 tests.append(TestUnixDomain) 5095 tests.extend([TIPCTest, TIPCThreadableTest])
4809 if sys.platform == 'linux':
4810 tests.append(TestLinuxAbstractNamespace)
4811 if isTipcAvailable():
4812 tests.append(TIPCTest)
4813 tests.append(TIPCThreadableTest)
4814 tests.extend([BasicCANTest, CANTest]) 5096 tests.extend([BasicCANTest, CANTest])
4815 tests.extend([BasicRDSTest, RDSTest]) 5097 tests.extend([BasicRDSTest, RDSTest])
4816 tests.extend([ 5098 tests.extend([
4817 CmsgMacroTests, 5099 CmsgMacroTests,
4818 SendmsgUDPTest, 5100 SendmsgUDPTest,
4819 RecvmsgUDPTest, 5101 RecvmsgUDPTest,
4820 RecvmsgIntoUDPTest, 5102 RecvmsgIntoUDPTest,
4821 SendmsgUDP6Test, 5103 SendmsgUDP6Test,
4822 RecvmsgUDP6Test, 5104 RecvmsgUDP6Test,
4823 RecvmsgRFC3542AncillaryUDP6Test, 5105 RecvmsgRFC3542AncillaryUDP6Test,
(...skipping 15 matching lines...) Expand all
4839 InterruptedSendTimeoutTest, 5121 InterruptedSendTimeoutTest,
4840 TestSocketSharing, 5122 TestSocketSharing,
4841 ]) 5123 ])
4842 5124
4843 thread_info = support.threading_setup() 5125 thread_info = support.threading_setup()
4844 support.run_unittest(*tests) 5126 support.run_unittest(*tests)
4845 support.threading_cleanup(*thread_info) 5127 support.threading_cleanup(*thread_info)
4846 5128
4847 if __name__ == "__main__": 5129 if __name__ == "__main__":
4848 test_main() 5130 test_main()
LEFTRIGHT

RSS Feeds Recent Issues | This issue
This is Rietveld 894c83f36cb7+