blob: 99707cec9b831c3736eb29134794044c2c6c6868 [file] [log] [blame]
Guido van Rossum24e4af82002-06-12 19:18:08 +00001import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002from test import support
Barry Warsawcf3d4b51997-01-03 20:03:32 +00003
Christian Heimes5e696852008-04-09 08:37:03 +00004import errno
Gregory P. Smithaafdca82010-01-04 04:50:36 +00005import io
Charles-François Natali65708cf2014-07-25 18:44:30 +01006import itertools
Barry Warsawcf3d4b51997-01-03 20:03:32 +00007import socket
Guido van Rossum24e4af82002-06-12 19:18:08 +00008import select
Nick Coghlan96fe56a2011-08-22 11:55:57 +10009import tempfile
Christian Heimesbbe741d2008-03-28 10:53:29 +000010import time
11import traceback
Alexandre Vassalottif260e442008-05-11 19:59:59 +000012import queue
Jack Jansen522e7692002-09-06 21:57:50 +000013import sys
Christian Heimesfaf2f632008-01-06 16:59:19 +000014import os
15import array
Antoine Pitrouacd0fda2010-10-23 17:01:44 +000016import platform
Antoine Pitrou4b92b5f2010-09-07 21:05:49 +000017import contextlib
Raymond Hettinger027bb632004-05-31 03:09:25 +000018from weakref import proxy
Thomas Wouters0e3f5912006-08-11 14:57:12 +000019import signal
Antoine Pitrou6d7df632010-09-27 17:52:25 +000020import math
Antoine Pitrou6d58d642011-03-20 23:56:36 +010021import pickle
Charles-François Natali47413c12011-10-06 19:47:44 +020022import struct
Giampaolo Rodola'915d1412014-06-11 03:54:30 +020023import random
24import string
Antoine Pitroub1c54962010-10-14 15:05:38 +000025try:
Kristján Valur Jónsson10f383a2012-04-07 11:23:31 +000026 import multiprocessing
27except ImportError:
28 multiprocessing = False
Victor Stinnera3c18d02013-09-08 11:53:09 +020029try:
30 import fcntl
31except ImportError:
32 fcntl = None
Barry Warsawcf3d4b51997-01-03 20:03:32 +000033
Benjamin Petersonee8712c2008-05-20 21:35:26 +000034HOST = support.HOST
Marc-André Lemburg8f36af72011-02-25 15:42:01 +000035MSG = 'Michael Gilfix was here\u1234\r\n'.encode('utf-8') ## test unicode string and carriage return
Barry Warsawcf3d4b51997-01-03 20:03:32 +000036
Victor Stinner45df8202010-04-28 22:31:17 +000037try:
38 import _thread as thread
39 import threading
40except ImportError:
41 thread = None
42 threading = None
Victor Stinnere254e532014-07-26 14:36:55 +020043try:
44 import _socket
45except ImportError:
46 _socket = None
47
Victor Stinner45df8202010-04-28 22:31:17 +000048
Charles-François Natali47413c12011-10-06 19:47:44 +020049def _have_socket_can():
50 """Check whether CAN sockets are supported on this host."""
51 try:
52 s = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
Andrew Svetlov0832af62012-12-18 23:10:48 +020053 except (AttributeError, OSError):
Charles-François Natali47413c12011-10-06 19:47:44 +020054 return False
55 else:
56 s.close()
57 return True
58
Charles-François Natali10b8cf42011-11-10 19:21:37 +010059def _have_socket_rds():
60 """Check whether RDS sockets are supported on this host."""
61 try:
62 s = socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0)
63 except (AttributeError, OSError):
64 return False
65 else:
66 s.close()
67 return True
68
Charles-François Natali47413c12011-10-06 19:47:44 +020069HAVE_SOCKET_CAN = _have_socket_can()
70
Charles-François Natali10b8cf42011-11-10 19:21:37 +010071HAVE_SOCKET_RDS = _have_socket_rds()
72
Nick Coghlan96fe56a2011-08-22 11:55:57 +100073# Size in bytes of the int type
74SIZEOF_INT = array.array("i").itemsize
75
Guido van Rossum24e4af82002-06-12 19:18:08 +000076class SocketTCPTest(unittest.TestCase):
Barry Warsawcf3d4b51997-01-03 20:03:32 +000077
Guido van Rossum24e4af82002-06-12 19:18:08 +000078 def setUp(self):
79 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +000080 self.port = support.bind_port(self.serv)
Charles-François Natali6e204602014-07-23 19:28:13 +010081 self.serv.listen()
Barry Warsawcf3d4b51997-01-03 20:03:32 +000082
Guido van Rossum24e4af82002-06-12 19:18:08 +000083 def tearDown(self):
84 self.serv.close()
85 self.serv = None
Barry Warsawcf3d4b51997-01-03 20:03:32 +000086
Guido van Rossum24e4af82002-06-12 19:18:08 +000087class SocketUDPTest(unittest.TestCase):
88
89 def setUp(self):
90 self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +000091 self.port = support.bind_port(self.serv)
Guido van Rossum24e4af82002-06-12 19:18:08 +000092
93 def tearDown(self):
94 self.serv.close()
95 self.serv = None
96
Nick Coghlan96fe56a2011-08-22 11:55:57 +100097class ThreadSafeCleanupTestCase(unittest.TestCase):
98 """Subclass of unittest.TestCase with thread-safe cleanup methods.
99
100 This subclass protects the addCleanup() and doCleanups() methods
101 with a recursive lock.
102 """
103
104 if threading:
105 def __init__(self, *args, **kwargs):
106 super().__init__(*args, **kwargs)
107 self._cleanup_lock = threading.RLock()
108
109 def addCleanup(self, *args, **kwargs):
110 with self._cleanup_lock:
111 return super().addCleanup(*args, **kwargs)
112
113 def doCleanups(self, *args, **kwargs):
114 with self._cleanup_lock:
115 return super().doCleanups(*args, **kwargs)
116
Charles-François Natali47413c12011-10-06 19:47:44 +0200117class SocketCANTest(unittest.TestCase):
118
119 """To be able to run this test, a `vcan0` CAN interface can be created with
120 the following commands:
121 # modprobe vcan
122 # ip link add dev vcan0 type vcan
123 # ifconfig vcan0 up
124 """
125 interface = 'vcan0'
126 bufsize = 128
127
Charles-François Natali773e42d2013-02-05 19:42:01 +0100128 """The CAN frame structure is defined in <linux/can.h>:
129
130 struct can_frame {
131 canid_t can_id; /* 32 bit CAN_ID + EFF/RTR/ERR flags */
132 __u8 can_dlc; /* data length code: 0 .. 8 */
133 __u8 data[8] __attribute__((aligned(8)));
134 };
135 """
136 can_frame_fmt = "=IB3x8s"
137 can_frame_size = struct.calcsize(can_frame_fmt)
138
139 """The Broadcast Management Command frame structure is defined
140 in <linux/can/bcm.h>:
141
142 struct bcm_msg_head {
143 __u32 opcode;
144 __u32 flags;
145 __u32 count;
146 struct timeval ival1, ival2;
147 canid_t can_id;
148 __u32 nframes;
149 struct can_frame frames[0];
150 }
151
152 `bcm_msg_head` must be 8 bytes aligned because of the `frames` member (see
153 `struct can_frame` definition). Must use native not standard types for packing.
154 """
155 bcm_cmd_msg_fmt = "@3I4l2I"
156 bcm_cmd_msg_fmt += "x" * (struct.calcsize(bcm_cmd_msg_fmt) % 8)
157
Charles-François Natali47413c12011-10-06 19:47:44 +0200158 def setUp(self):
159 self.s = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
Antoine Pitrou86fe8602011-10-10 20:15:59 +0200160 self.addCleanup(self.s.close)
Charles-François Natali47413c12011-10-06 19:47:44 +0200161 try:
162 self.s.bind((self.interface,))
Andrew Svetlov0832af62012-12-18 23:10:48 +0200163 except OSError:
Charles-François Natali47413c12011-10-06 19:47:44 +0200164 self.skipTest('network interface `%s` does not exist' %
165 self.interface)
Charles-François Natali47413c12011-10-06 19:47:44 +0200166
Charles-François Natali10b8cf42011-11-10 19:21:37 +0100167
168class SocketRDSTest(unittest.TestCase):
169
170 """To be able to run this test, the `rds` kernel module must be loaded:
171 # modprobe rds
172 """
173 bufsize = 8192
174
175 def setUp(self):
176 self.serv = socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0)
177 self.addCleanup(self.serv.close)
178 try:
179 self.port = support.bind_port(self.serv)
180 except OSError:
181 self.skipTest('unable to bind RDS socket')
182
183
Guido van Rossum24e4af82002-06-12 19:18:08 +0000184class ThreadableTest:
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000185 """Threadable Test class
186
187 The ThreadableTest class makes it easy to create a threaded
188 client/server pair from an existing unit test. To create a
189 new threaded class from an existing unit test, use multiple
190 inheritance:
191
192 class NewClass (OldClass, ThreadableTest):
193 pass
194
195 This class defines two new fixture functions with obvious
196 purposes for overriding:
197
198 clientSetUp ()
199 clientTearDown ()
200
201 Any new test functions within the class must then define
202 tests in pairs, where the test name is preceeded with a
203 '_' to indicate the client portion of the test. Ex:
204
205 def testFoo(self):
206 # Server portion
207
208 def _testFoo(self):
209 # Client portion
210
211 Any exceptions raised by the clients during their tests
212 are caught and transferred to the main thread to alert
213 the testing framework.
214
215 Note, the server setup function cannot call any blocking
216 functions that rely on the client thread during setup,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000217 unless serverExplicitReady() is called just before
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000218 the blocking call (such as in setting up a client/server
219 connection and performing the accept() in setUp().
220 """
Guido van Rossum24e4af82002-06-12 19:18:08 +0000221
222 def __init__(self):
223 # Swap the true setup function
224 self.__setUp = self.setUp
225 self.__tearDown = self.tearDown
226 self.setUp = self._setUp
227 self.tearDown = self._tearDown
228
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000229 def serverExplicitReady(self):
230 """This method allows the server to explicitly indicate that
231 it wants the client thread to proceed. This is useful if the
232 server is about to execute a blocking routine that is
233 dependent upon the client thread during its setup routine."""
234 self.server_ready.set()
235
Guido van Rossum24e4af82002-06-12 19:18:08 +0000236 def _setUp(self):
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000237 self.server_ready = threading.Event()
238 self.client_ready = threading.Event()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000239 self.done = threading.Event()
Alexandre Vassalottif260e442008-05-11 19:59:59 +0000240 self.queue = queue.Queue(1)
Antoine Pitrou86fe8602011-10-10 20:15:59 +0200241 self.server_crashed = False
Guido van Rossum24e4af82002-06-12 19:18:08 +0000242
243 # Do some munging to start the client test.
Guido van Rossum11ba0942002-06-13 15:07:44 +0000244 methodname = self.id()
245 i = methodname.rfind('.')
246 methodname = methodname[i+1:]
247 test_method = getattr(self, '_' + methodname)
Guido van Rossumab659962002-06-12 21:29:43 +0000248 self.client_thread = thread.start_new_thread(
249 self.clientRun, (test_method,))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000250
Antoine Pitrou86fe8602011-10-10 20:15:59 +0200251 try:
252 self.__setUp()
253 except:
254 self.server_crashed = True
255 raise
256 finally:
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000257 self.server_ready.set()
258 self.client_ready.wait()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000259
260 def _tearDown(self):
261 self.__tearDown()
262 self.done.wait()
263
Raymond Hettingerda3caed2008-01-14 21:39:24 +0000264 if self.queue.qsize():
Antoine Pitrou98b46702010-09-18 22:59:00 +0000265 exc = self.queue.get()
266 raise exc
Guido van Rossum24e4af82002-06-12 19:18:08 +0000267
268 def clientRun(self, test_func):
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000269 self.server_ready.wait()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000270 self.clientSetUp()
Charles-François Natalia49ed762011-09-21 22:03:58 +0200271 self.client_ready.set()
Antoine Pitrou86fe8602011-10-10 20:15:59 +0200272 if self.server_crashed:
273 self.clientTearDown()
274 return
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000275 if not hasattr(test_func, '__call__'):
Collin Winter3add4d72007-08-29 23:37:32 +0000276 raise TypeError("test_func must be a callable function")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000277 try:
278 test_func()
Antoine Pitrou98b46702010-09-18 22:59:00 +0000279 except BaseException as e:
280 self.queue.put(e)
281 finally:
282 self.clientTearDown()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000283
284 def clientSetUp(self):
Collin Winter3add4d72007-08-29 23:37:32 +0000285 raise NotImplementedError("clientSetUp must be implemented.")
Guido van Rossum24e4af82002-06-12 19:18:08 +0000286
287 def clientTearDown(self):
288 self.done.set()
289 thread.exit()
290
291class ThreadedTCPSocketTest(SocketTCPTest, ThreadableTest):
292
293 def __init__(self, methodName='runTest'):
294 SocketTCPTest.__init__(self, methodName=methodName)
295 ThreadableTest.__init__(self)
296
297 def clientSetUp(self):
298 self.cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
299
300 def clientTearDown(self):
301 self.cli.close()
302 self.cli = None
303 ThreadableTest.clientTearDown(self)
304
305class ThreadedUDPSocketTest(SocketUDPTest, ThreadableTest):
306
307 def __init__(self, methodName='runTest'):
308 SocketUDPTest.__init__(self, methodName=methodName)
309 ThreadableTest.__init__(self)
310
311 def clientSetUp(self):
312 self.cli = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
313
Brian Curtin3beb38f2010-11-04 03:41:43 +0000314 def clientTearDown(self):
315 self.cli.close()
316 self.cli = None
317 ThreadableTest.clientTearDown(self)
318
Charles-François Natali47413c12011-10-06 19:47:44 +0200319class ThreadedCANSocketTest(SocketCANTest, ThreadableTest):
320
321 def __init__(self, methodName='runTest'):
322 SocketCANTest.__init__(self, methodName=methodName)
323 ThreadableTest.__init__(self)
324
325 def clientSetUp(self):
326 self.cli = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
327 try:
328 self.cli.bind((self.interface,))
Andrew Svetlov0832af62012-12-18 23:10:48 +0200329 except OSError:
Antoine Pitrou86fe8602011-10-10 20:15:59 +0200330 # skipTest should not be called here, and will be called in the
331 # server instead
332 pass
Charles-François Natali47413c12011-10-06 19:47:44 +0200333
334 def clientTearDown(self):
335 self.cli.close()
336 self.cli = None
337 ThreadableTest.clientTearDown(self)
338
Charles-François Natali10b8cf42011-11-10 19:21:37 +0100339class ThreadedRDSSocketTest(SocketRDSTest, ThreadableTest):
340
341 def __init__(self, methodName='runTest'):
342 SocketRDSTest.__init__(self, methodName=methodName)
343 ThreadableTest.__init__(self)
Charles-François Natali10b8cf42011-11-10 19:21:37 +0100344
345 def clientSetUp(self):
346 self.cli = socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0)
347 try:
348 # RDS sockets must be bound explicitly to send or receive data
349 self.cli.bind((HOST, 0))
350 self.cli_addr = self.cli.getsockname()
351 except OSError:
352 # skipTest should not be called here, and will be called in the
353 # server instead
354 pass
355
356 def clientTearDown(self):
357 self.cli.close()
358 self.cli = None
359 ThreadableTest.clientTearDown(self)
360
Guido van Rossum24e4af82002-06-12 19:18:08 +0000361class SocketConnectedTest(ThreadedTCPSocketTest):
Jeremy Hylton5accbdb2007-08-03 20:40:09 +0000362 """Socket tests for client-server connection.
363
364 self.cli_conn is a client socket connected to the server. The
365 setUp() method guarantees that it is connected to the server.
366 """
Guido van Rossum24e4af82002-06-12 19:18:08 +0000367
368 def __init__(self, methodName='runTest'):
369 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
370
371 def setUp(self):
372 ThreadedTCPSocketTest.setUp(self)
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000373 # Indicate explicitly we're ready for the client thread to
374 # proceed and then perform the blocking call to accept
375 self.serverExplicitReady()
Guido van Rossum24e4af82002-06-12 19:18:08 +0000376 conn, addr = self.serv.accept()
377 self.cli_conn = conn
378
379 def tearDown(self):
380 self.cli_conn.close()
381 self.cli_conn = None
382 ThreadedTCPSocketTest.tearDown(self)
383
384 def clientSetUp(self):
385 ThreadedTCPSocketTest.clientSetUp(self)
Christian Heimes5e696852008-04-09 08:37:03 +0000386 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +0000387 self.serv_conn = self.cli
388
389 def clientTearDown(self):
390 self.serv_conn.close()
391 self.serv_conn = None
392 ThreadedTCPSocketTest.clientTearDown(self)
393
Dave Cole331708b2004-08-09 04:51:41 +0000394class SocketPairTest(unittest.TestCase, ThreadableTest):
395
396 def __init__(self, methodName='runTest'):
397 unittest.TestCase.__init__(self, methodName=methodName)
398 ThreadableTest.__init__(self)
399
400 def setUp(self):
401 self.serv, self.cli = socket.socketpair()
402
403 def tearDown(self):
404 self.serv.close()
405 self.serv = None
406
407 def clientSetUp(self):
408 pass
409
410 def clientTearDown(self):
411 self.cli.close()
412 self.cli = None
413 ThreadableTest.clientTearDown(self)
414
Tim Peters494aaee2004-08-09 18:54:11 +0000415
Nick Coghlan96fe56a2011-08-22 11:55:57 +1000416# The following classes are used by the sendmsg()/recvmsg() tests.
417# Combining, for instance, ConnectedStreamTestMixin and TCPTestBase
418# gives a drop-in replacement for SocketConnectedTest, but different
419# address families can be used, and the attributes serv_addr and
420# cli_addr will be set to the addresses of the endpoints.
421
422class SocketTestBase(unittest.TestCase):
423 """A base class for socket tests.
424
425 Subclasses must provide methods newSocket() to return a new socket
426 and bindSock(sock) to bind it to an unused address.
427
428 Creates a socket self.serv and sets self.serv_addr to its address.
429 """
430
431 def setUp(self):
432 self.serv = self.newSocket()
433 self.bindServer()
434
435 def bindServer(self):
436 """Bind server socket and set self.serv_addr to its address."""
437 self.bindSock(self.serv)
438 self.serv_addr = self.serv.getsockname()
439
440 def tearDown(self):
441 self.serv.close()
442 self.serv = None
443
444
445class SocketListeningTestMixin(SocketTestBase):
446 """Mixin to listen on the server socket."""
447
448 def setUp(self):
449 super().setUp()
Charles-François Natali6e204602014-07-23 19:28:13 +0100450 self.serv.listen()
Nick Coghlan96fe56a2011-08-22 11:55:57 +1000451
452
453class ThreadedSocketTestMixin(ThreadSafeCleanupTestCase, SocketTestBase,
454 ThreadableTest):
455 """Mixin to add client socket and allow client/server tests.
456
457 Client socket is self.cli and its address is self.cli_addr. See
458 ThreadableTest for usage information.
459 """
460
461 def __init__(self, *args, **kwargs):
462 super().__init__(*args, **kwargs)
463 ThreadableTest.__init__(self)
464
465 def clientSetUp(self):
466 self.cli = self.newClientSocket()
467 self.bindClient()
468
469 def newClientSocket(self):
470 """Return a new socket for use as client."""
471 return self.newSocket()
472
473 def bindClient(self):
474 """Bind client socket and set self.cli_addr to its address."""
475 self.bindSock(self.cli)
476 self.cli_addr = self.cli.getsockname()
477
478 def clientTearDown(self):
479 self.cli.close()
480 self.cli = None
481 ThreadableTest.clientTearDown(self)
482
483
484class ConnectedStreamTestMixin(SocketListeningTestMixin,
485 ThreadedSocketTestMixin):
486 """Mixin to allow client/server stream tests with connected client.
487
488 Server's socket representing connection to client is self.cli_conn
489 and client's connection to server is self.serv_conn. (Based on
490 SocketConnectedTest.)
491 """
492
493 def setUp(self):
494 super().setUp()
495 # Indicate explicitly we're ready for the client thread to
496 # proceed and then perform the blocking call to accept
497 self.serverExplicitReady()
498 conn, addr = self.serv.accept()
499 self.cli_conn = conn
500
501 def tearDown(self):
502 self.cli_conn.close()
503 self.cli_conn = None
504 super().tearDown()
505
506 def clientSetUp(self):
507 super().clientSetUp()
508 self.cli.connect(self.serv_addr)
509 self.serv_conn = self.cli
510
511 def clientTearDown(self):
512 self.serv_conn.close()
513 self.serv_conn = None
514 super().clientTearDown()
515
516
517class UnixSocketTestBase(SocketTestBase):
518 """Base class for Unix-domain socket tests."""
519
520 # This class is used for file descriptor passing tests, so we
521 # create the sockets in a private directory so that other users
522 # can't send anything that might be problematic for a privileged
523 # user running the tests.
524
525 def setUp(self):
526 self.dir_path = tempfile.mkdtemp()
527 self.addCleanup(os.rmdir, self.dir_path)
528 super().setUp()
529
530 def bindSock(self, sock):
531 path = tempfile.mktemp(dir=self.dir_path)
532 sock.bind(path)
533 self.addCleanup(support.unlink, path)
534
535class UnixStreamBase(UnixSocketTestBase):
536 """Base class for Unix-domain SOCK_STREAM tests."""
537
538 def newSocket(self):
539 return socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
540
541
542class InetTestBase(SocketTestBase):
543 """Base class for IPv4 socket tests."""
544
545 host = HOST
546
547 def setUp(self):
548 super().setUp()
549 self.port = self.serv_addr[1]
550
551 def bindSock(self, sock):
552 support.bind_port(sock, host=self.host)
553
554class TCPTestBase(InetTestBase):
555 """Base class for TCP-over-IPv4 tests."""
556
557 def newSocket(self):
558 return socket.socket(socket.AF_INET, socket.SOCK_STREAM)
559
560class UDPTestBase(InetTestBase):
561 """Base class for UDP-over-IPv4 tests."""
562
563 def newSocket(self):
564 return socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
565
566class SCTPStreamBase(InetTestBase):
567 """Base class for SCTP tests in one-to-one (SOCK_STREAM) mode."""
568
569 def newSocket(self):
570 return socket.socket(socket.AF_INET, socket.SOCK_STREAM,
571 socket.IPPROTO_SCTP)
572
573
574class Inet6TestBase(InetTestBase):
575 """Base class for IPv6 socket tests."""
576
Charles-François Natalifcfb3242013-08-31 14:40:49 +0200577 host = support.HOSTv6
Nick Coghlan96fe56a2011-08-22 11:55:57 +1000578
579class UDP6TestBase(Inet6TestBase):
580 """Base class for UDP-over-IPv6 tests."""
581
582 def newSocket(self):
583 return socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
584
585
586# Test-skipping decorators for use with ThreadableTest.
587
588def skipWithClientIf(condition, reason):
589 """Skip decorated test if condition is true, add client_skip decorator.
590
591 If the decorated object is not a class, sets its attribute
592 "client_skip" to a decorator which will return an empty function
593 if the test is to be skipped, or the original function if it is
594 not. This can be used to avoid running the client part of a
595 skipped test when using ThreadableTest.
596 """
597 def client_pass(*args, **kwargs):
598 pass
599 def skipdec(obj):
600 retval = unittest.skip(reason)(obj)
601 if not isinstance(obj, type):
602 retval.client_skip = lambda f: client_pass
603 return retval
604 def noskipdec(obj):
605 if not (isinstance(obj, type) or hasattr(obj, "client_skip")):
606 obj.client_skip = lambda f: f
607 return obj
608 return skipdec if condition else noskipdec
609
610
611def requireAttrs(obj, *attributes):
612 """Skip decorated test if obj is missing any of the given attributes.
613
614 Sets client_skip attribute as skipWithClientIf() does.
615 """
616 missing = [name for name in attributes if not hasattr(obj, name)]
617 return skipWithClientIf(
618 missing, "don't have " + ", ".join(name for name in missing))
619
620
621def requireSocket(*args):
622 """Skip decorated test if a socket cannot be created with given arguments.
623
624 When an argument is given as a string, will use the value of that
625 attribute of the socket module, or skip the test if it doesn't
626 exist. Sets client_skip attribute as skipWithClientIf() does.
627 """
628 err = None
629 missing = [obj for obj in args if
630 isinstance(obj, str) and not hasattr(socket, obj)]
631 if missing:
632 err = "don't have " + ", ".join(name for name in missing)
633 else:
634 callargs = [getattr(socket, obj) if isinstance(obj, str) else obj
635 for obj in args]
636 try:
637 s = socket.socket(*callargs)
Andrew Svetlov0832af62012-12-18 23:10:48 +0200638 except OSError as e:
Nick Coghlan96fe56a2011-08-22 11:55:57 +1000639 # XXX: check errno?
640 err = str(e)
641 else:
642 s.close()
643 return skipWithClientIf(
644 err is not None,
645 "can't create socket({0}): {1}".format(
646 ", ".join(str(o) for o in args), err))
647
648
Guido van Rossum24e4af82002-06-12 19:18:08 +0000649#######################################################################
650## Begin Tests
651
652class GeneralModuleTests(unittest.TestCase):
653
Ethan Furman7184bac2014-10-14 18:56:53 -0700654 def test_SocketType_is_socketobject(self):
655 import _socket
656 self.assertTrue(socket.SocketType is _socket.socket)
657 s = socket.socket()
658 self.assertIsInstance(s, socket.SocketType)
659 s.close()
660
Walter Dörwalda7eb93e2007-06-05 13:41:53 +0000661 def test_repr(self):
662 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Giampaolo Rodola'50331cb2013-04-10 15:49:47 +0200663 with s:
664 self.assertIn('fd=%i' % s.fileno(), repr(s))
Nick Coghlanca351e62013-11-13 22:10:16 +1000665 self.assertIn('family=%s' % socket.AF_INET, repr(s))
666 self.assertIn('type=%s' % socket.SOCK_STREAM, repr(s))
Giampaolo Rodola'50331cb2013-04-10 15:49:47 +0200667 self.assertIn('proto=0', repr(s))
Giampaolo Rodola'50331cb2013-04-10 15:49:47 +0200668 self.assertNotIn('raddr', repr(s))
669 s.bind(('127.0.0.1', 0))
Giampaolo Rodola'7ca49362013-04-12 18:28:15 +0200670 self.assertIn('laddr', repr(s))
Giampaolo Rodola'50331cb2013-04-10 15:49:47 +0200671 self.assertIn(str(s.getsockname()), repr(s))
672 self.assertIn('[closed]', repr(s))
673 self.assertNotIn('laddr', repr(s))
Walter Dörwalda7eb93e2007-06-05 13:41:53 +0000674
Victor Stinnere254e532014-07-26 14:36:55 +0200675 @unittest.skipUnless(_socket is not None, 'need _socket module')
676 def test_csocket_repr(self):
677 s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
678 try:
679 expected = ('<socket object, fd=%s, family=%s, type=%s, proto=%s>'
680 % (s.fileno(), s.family, s.type, s.proto))
681 self.assertEqual(repr(s), expected)
682 finally:
683 s.close()
684 expected = ('<socket object, fd=-1, family=%s, type=%s, proto=%s>'
685 % (s.family, s.type, s.proto))
686 self.assertEqual(repr(s), expected)
687
Raymond Hettinger027bb632004-05-31 03:09:25 +0000688 def test_weakref(self):
689 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
690 p = proxy(s)
691 self.assertEqual(p.fileno(), s.fileno())
692 s.close()
693 s = None
694 try:
695 p.fileno()
696 except ReferenceError:
697 pass
698 else:
699 self.fail('Socket proxy still exists')
700
Guido van Rossum24e4af82002-06-12 19:18:08 +0000701 def testSocketError(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000702 # Testing socket module exceptions
Ezio Melotti845f1522011-05-08 20:23:57 +0300703 msg = "Error raising socket exception (%s)."
Andrew Svetlov0832af62012-12-18 23:10:48 +0200704 with self.assertRaises(OSError, msg=msg % 'OSError'):
705 raise OSError
706 with self.assertRaises(OSError, msg=msg % 'socket.herror'):
Guido van Rossum24e4af82002-06-12 19:18:08 +0000707 raise socket.herror
Andrew Svetlov0832af62012-12-18 23:10:48 +0200708 with self.assertRaises(OSError, msg=msg % 'socket.gaierror'):
Guido van Rossum24e4af82002-06-12 19:18:08 +0000709 raise socket.gaierror
Guido van Rossum24e4af82002-06-12 19:18:08 +0000710
Ezio Melotti63e42302011-05-07 19:47:48 +0300711 def testSendtoErrors(self):
Berker Peksag4882cac2015-04-14 09:30:01 +0300712 # Testing that sendto doesn't masks failures. See #10169.
Ezio Melotti63e42302011-05-07 19:47:48 +0300713 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
714 self.addCleanup(s.close)
715 s.bind(('', 0))
716 sockname = s.getsockname()
717 # 2 args
Ezio Melotti4c1aebd2011-05-07 19:50:28 +0300718 with self.assertRaises(TypeError) as cm:
Ezio Melotti63e42302011-05-07 19:47:48 +0300719 s.sendto('\u2620', sockname)
Ezio Melotti4c1aebd2011-05-07 19:50:28 +0300720 self.assertEqual(str(cm.exception),
R David Murray861470c2014-10-05 11:47:01 -0400721 "a bytes-like object is required, not 'str'")
Ezio Melotti4c1aebd2011-05-07 19:50:28 +0300722 with self.assertRaises(TypeError) as cm:
Ezio Melotti63e42302011-05-07 19:47:48 +0300723 s.sendto(5j, sockname)
Ezio Melotti4c1aebd2011-05-07 19:50:28 +0300724 self.assertEqual(str(cm.exception),
R David Murray861470c2014-10-05 11:47:01 -0400725 "a bytes-like object is required, not 'complex'")
Ezio Melotti4c1aebd2011-05-07 19:50:28 +0300726 with self.assertRaises(TypeError) as cm:
Ezio Melotti63e42302011-05-07 19:47:48 +0300727 s.sendto(b'foo', None)
Ezio Melotti4c1aebd2011-05-07 19:50:28 +0300728 self.assertIn('not NoneType',str(cm.exception))
Ezio Melotti63e42302011-05-07 19:47:48 +0300729 # 3 args
Ezio Melotti4c1aebd2011-05-07 19:50:28 +0300730 with self.assertRaises(TypeError) as cm:
Ezio Melotti63e42302011-05-07 19:47:48 +0300731 s.sendto('\u2620', 0, sockname)
Ezio Melotti4c1aebd2011-05-07 19:50:28 +0300732 self.assertEqual(str(cm.exception),
R David Murray861470c2014-10-05 11:47:01 -0400733 "a bytes-like object is required, not 'str'")
Ezio Melotti4c1aebd2011-05-07 19:50:28 +0300734 with self.assertRaises(TypeError) as cm:
Ezio Melotti63e42302011-05-07 19:47:48 +0300735 s.sendto(5j, 0, sockname)
Ezio Melotti4c1aebd2011-05-07 19:50:28 +0300736 self.assertEqual(str(cm.exception),
R David Murray861470c2014-10-05 11:47:01 -0400737 "a bytes-like object is required, not 'complex'")
Ezio Melotti4c1aebd2011-05-07 19:50:28 +0300738 with self.assertRaises(TypeError) as cm:
Ezio Melotti63e42302011-05-07 19:47:48 +0300739 s.sendto(b'foo', 0, None)
Ezio Melotti4c1aebd2011-05-07 19:50:28 +0300740 self.assertIn('not NoneType', str(cm.exception))
741 with self.assertRaises(TypeError) as cm:
Ezio Melotti63e42302011-05-07 19:47:48 +0300742 s.sendto(b'foo', 'bar', sockname)
Ezio Melotti4c1aebd2011-05-07 19:50:28 +0300743 self.assertIn('an integer is required', str(cm.exception))
744 with self.assertRaises(TypeError) as cm:
Ezio Melotti63e42302011-05-07 19:47:48 +0300745 s.sendto(b'foo', None, None)
Ezio Melotti4c1aebd2011-05-07 19:50:28 +0300746 self.assertIn('an integer is required', str(cm.exception))
Ezio Melotti63e42302011-05-07 19:47:48 +0300747 # wrong number of args
Ezio Melotti4c1aebd2011-05-07 19:50:28 +0300748 with self.assertRaises(TypeError) as cm:
Ezio Melotti63e42302011-05-07 19:47:48 +0300749 s.sendto(b'foo')
Ezio Melotti4c1aebd2011-05-07 19:50:28 +0300750 self.assertIn('(1 given)', str(cm.exception))
751 with self.assertRaises(TypeError) as cm:
Ezio Melotti63e42302011-05-07 19:47:48 +0300752 s.sendto(b'foo', 0, sockname, 4)
Ezio Melotti4c1aebd2011-05-07 19:50:28 +0300753 self.assertIn('(4 given)', str(cm.exception))
Ezio Melotti63e42302011-05-07 19:47:48 +0300754
Guido van Rossum24e4af82002-06-12 19:18:08 +0000755 def testCrucialConstants(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000756 # Testing for mission critical constants
Guido van Rossum24e4af82002-06-12 19:18:08 +0000757 socket.AF_INET
758 socket.SOCK_STREAM
759 socket.SOCK_DGRAM
760 socket.SOCK_RAW
761 socket.SOCK_RDM
762 socket.SOCK_SEQPACKET
763 socket.SOL_SOCKET
764 socket.SO_REUSEADDR
765
Guido van Rossum654c11e2002-06-13 20:24:17 +0000766 def testHostnameRes(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000767 # Testing hostname resolution mechanisms
Guido van Rossum654c11e2002-06-13 20:24:17 +0000768 hostname = socket.gethostname()
Guido van Rossum71e02942002-12-26 16:55:15 +0000769 try:
770 ip = socket.gethostbyname(hostname)
Andrew Svetlov0832af62012-12-18 23:10:48 +0200771 except OSError:
Guido van Rossum71e02942002-12-26 16:55:15 +0000772 # Probably name lookup wasn't set up right; skip this test
Zachary Ware9fe6d862013-12-08 00:20:35 -0600773 self.skipTest('name lookup failure')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000774 self.assertTrue(ip.find('.') >= 0, "Error resolving host to ip.")
Guido van Rossum9647b522002-12-26 17:04:45 +0000775 try:
776 hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
Andrew Svetlov0832af62012-12-18 23:10:48 +0200777 except OSError:
Guido van Rossum9647b522002-12-26 17:04:45 +0000778 # Probably a similar problem as above; skip this test
Zachary Ware9fe6d862013-12-08 00:20:35 -0600779 self.skipTest('name lookup failure')
Brett Cannon01668a12005-03-11 00:04:17 +0000780 all_host_names = [hostname, hname] + aliases
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000781 fqhn = socket.getfqdn(ip)
Guido van Rossum654c11e2002-06-13 20:24:17 +0000782 if not fqhn in all_host_names:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000783 self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names)))
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000784
Charles-François Natali0cc86852013-09-13 19:53:08 +0200785 def test_host_resolution(self):
786 for addr in ['0.1.1.~1', '1+.1.1.1', '::1q', '::1::2',
787 '1:1:1:1:1:1:1:1:1']:
788 self.assertRaises(OSError, socket.gethostbyname, addr)
789 self.assertRaises(OSError, socket.gethostbyaddr, addr)
790
791 for addr in [support.HOST, '10.0.0.1', '255.255.255.255']:
792 self.assertEqual(socket.gethostbyname(addr), addr)
793
794 # we don't test support.HOSTv6 because there's a chance it doesn't have
795 # a matching name entry (e.g. 'ip6-localhost')
796 for host in [support.HOST]:
797 self.assertIn(host, socket.gethostbyaddr(host)[2])
798
Antoine Pitrou061cfb52011-02-28 22:25:22 +0000799 @unittest.skipUnless(hasattr(socket, 'sethostname'), "test needs socket.sethostname()")
800 @unittest.skipUnless(hasattr(socket, 'gethostname'), "test needs socket.gethostname()")
801 def test_sethostname(self):
802 oldhn = socket.gethostname()
803 try:
804 socket.sethostname('new')
Andrew Svetlov0832af62012-12-18 23:10:48 +0200805 except OSError as e:
Antoine Pitrou061cfb52011-02-28 22:25:22 +0000806 if e.errno == errno.EPERM:
807 self.skipTest("test should be run as root")
808 else:
809 raise
810 try:
811 # running test as root!
812 self.assertEqual(socket.gethostname(), 'new')
813 # Should work with bytes objects too
814 socket.sethostname(b'bar')
815 self.assertEqual(socket.gethostname(), 'bar')
816 finally:
817 socket.sethostname(oldhn)
818
Gregory P. Smith5ed2e772011-05-15 00:26:45 -0700819 @unittest.skipUnless(hasattr(socket, 'if_nameindex'),
820 'socket.if_nameindex() not available.')
821 def testInterfaceNameIndex(self):
822 interfaces = socket.if_nameindex()
823 for index, name in interfaces:
Charles-François Natali60713592011-05-20 16:55:06 +0200824 self.assertIsInstance(index, int)
825 self.assertIsInstance(name, str)
Gregory P. Smith5ed2e772011-05-15 00:26:45 -0700826 # interface indices are non-zero integers
827 self.assertGreater(index, 0)
Charles-François Natali60713592011-05-20 16:55:06 +0200828 _index = socket.if_nametoindex(name)
829 self.assertIsInstance(_index, int)
830 self.assertEqual(index, _index)
831 _name = socket.if_indextoname(index)
832 self.assertIsInstance(_name, str)
833 self.assertEqual(name, _name)
834
835 @unittest.skipUnless(hasattr(socket, 'if_nameindex'),
836 'socket.if_nameindex() not available.')
837 def testInvalidInterfaceNameIndex(self):
838 # test nonexistent interface index/name
Andrew Svetlov0832af62012-12-18 23:10:48 +0200839 self.assertRaises(OSError, socket.if_indextoname, 0)
840 self.assertRaises(OSError, socket.if_nametoindex, '_DEADBEEF')
Charles-François Natali60713592011-05-20 16:55:06 +0200841 # test with invalid values
842 self.assertRaises(TypeError, socket.if_nametoindex, 0)
843 self.assertRaises(TypeError, socket.if_indextoname, '_DEADBEEF')
Gregory P. Smith5ed2e772011-05-15 00:26:45 -0700844
Serhiy Storchaka43767632013-11-03 21:31:38 +0200845 @unittest.skipUnless(hasattr(sys, 'getrefcount'),
846 'test needs sys.getrefcount()')
Guido van Rossum284a2cf2002-06-12 21:19:40 +0000847 def testRefCountGetNameInfo(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000848 # Testing reference count for getnameinfo
Serhiy Storchaka43767632013-11-03 21:31:38 +0200849 try:
850 # On some versions, this loses a reference
851 orig = sys.getrefcount(__name__)
852 socket.getnameinfo(__name__,0)
853 except TypeError:
854 if sys.getrefcount(__name__) != orig:
855 self.fail("socket.getnameinfo loses a reference")
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000856
Guido van Rossum24e4af82002-06-12 19:18:08 +0000857 def testInterpreterCrash(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000858 # Making sure getnameinfo doesn't crash the interpreter
Guido van Rossum24e4af82002-06-12 19:18:08 +0000859 try:
860 # On some versions, this crashes the interpreter.
861 socket.getnameinfo(('x', 0, 0, 0), 0)
Andrew Svetlov0832af62012-12-18 23:10:48 +0200862 except OSError:
Guido van Rossum24e4af82002-06-12 19:18:08 +0000863 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +0000864
Guido van Rossumc0a0e082002-09-16 01:30:03 +0000865 def testNtoH(self):
Guido van Rossuma2627af2002-09-14 00:58:46 +0000866 # This just checks that htons etc. are their own inverse,
867 # when looking at the lower 16 or 32 bits.
868 sizes = {socket.htonl: 32, socket.ntohl: 32,
869 socket.htons: 16, socket.ntohs: 16}
870 for func, size in sizes.items():
Guido van Rossume2a383d2007-01-15 16:59:06 +0000871 mask = (1<<size) - 1
Guido van Rossuma2627af2002-09-14 00:58:46 +0000872 for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210):
873 self.assertEqual(i & mask, func(func(i&mask)) & mask)
Jeremy Hyltoncbd5b892002-07-31 15:57:39 +0000874
Guido van Rossuma2627af2002-09-14 00:58:46 +0000875 swapped = func(mask)
876 self.assertEqual(swapped & mask, mask)
Guido van Rossume2a383d2007-01-15 16:59:06 +0000877 self.assertRaises(OverflowError, func, 1<<34)
Jeremy Hyltonc075e192002-07-25 16:01:12 +0000878
Guido van Rossum018919a2007-01-15 00:07:32 +0000879 def testNtoHErrors(self):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000880 good_values = [ 1, 2, 3, 1, 2, 3 ]
881 bad_values = [ -1, -2, -3, -1, -2, -3 ]
Guido van Rossum018919a2007-01-15 00:07:32 +0000882 for k in good_values:
883 socket.ntohl(k)
884 socket.ntohs(k)
885 socket.htonl(k)
886 socket.htons(k)
887 for k in bad_values:
888 self.assertRaises(OverflowError, socket.ntohl, k)
889 self.assertRaises(OverflowError, socket.ntohs, k)
890 self.assertRaises(OverflowError, socket.htonl, k)
891 self.assertRaises(OverflowError, socket.htons, k)
892
Barry Warsaw11b91a02004-06-28 00:50:43 +0000893 def testGetServBy(self):
894 eq = self.assertEqual
895 # Find one service that exists, then check all the related interfaces.
896 # I've ordered this by protocols that have both a tcp and udp
897 # protocol, at least for modern Linuxes.
doko@ubuntu.com4a173bc2014-04-17 19:47:16 +0200898 if (sys.platform.startswith(('freebsd', 'netbsd', 'gnukfreebsd'))
Victor Stinnere6747472011-08-21 00:39:18 +0200899 or sys.platform in ('linux', 'darwin')):
Andrew MacIntyre18bf43c2004-07-12 12:10:30 +0000900 # avoid the 'echo' service on this platform, as there is an
901 # assumption breaking non-standard port/protocol entry
902 services = ('daytime', 'qotd', 'domain')
903 else:
904 services = ('echo', 'daytime', 'domain')
905 for service in services:
Skip Montanarof4433302002-08-02 15:52:30 +0000906 try:
Barry Warsaw11b91a02004-06-28 00:50:43 +0000907 port = socket.getservbyname(service, 'tcp')
Skip Montanarof4433302002-08-02 15:52:30 +0000908 break
Andrew Svetlov0832af62012-12-18 23:10:48 +0200909 except OSError:
Skip Montanarof4433302002-08-02 15:52:30 +0000910 pass
Skip Montanaro05eb4012004-02-10 15:51:15 +0000911 else:
Andrew Svetlov0832af62012-12-18 23:10:48 +0200912 raise OSError
Barry Warsaw11b91a02004-06-28 00:50:43 +0000913 # Try same call with optional protocol omitted
914 port2 = socket.getservbyname(service)
915 eq(port, port2)
Terry Jan Reedyc30b7b12013-03-11 17:57:08 -0400916 # Try udp, but don't barf if it doesn't exist
Barry Warsaw11b91a02004-06-28 00:50:43 +0000917 try:
918 udpport = socket.getservbyname(service, 'udp')
Andrew Svetlov0832af62012-12-18 23:10:48 +0200919 except OSError:
Barry Warsaw11b91a02004-06-28 00:50:43 +0000920 udpport = None
921 else:
922 eq(udpport, port)
923 # Now make sure the lookup by port returns the same service name
924 eq(socket.getservbyport(port2), service)
925 eq(socket.getservbyport(port, 'tcp'), service)
926 if udpport is not None:
927 eq(socket.getservbyport(udpport, 'udp'), service)
Benjamin Peterson5c6d7872009-02-06 02:40:07 +0000928 # Make sure getservbyport does not accept out of range ports.
929 self.assertRaises(OverflowError, socket.getservbyport, -1)
930 self.assertRaises(OverflowError, socket.getservbyport, 65536)
Guido van Rossum24e4af82002-06-12 19:18:08 +0000931
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000932 def testDefaultTimeout(self):
Guido van Rossum8c943832002-08-08 01:00:28 +0000933 # Testing default timeout
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +0000934 # The default timeout should initially be None
935 self.assertEqual(socket.getdefaulttimeout(), None)
936 s = socket.socket()
937 self.assertEqual(s.gettimeout(), None)
938 s.close()
939
940 # Set the default timeout to 10, and see if it propagates
941 socket.setdefaulttimeout(10)
942 self.assertEqual(socket.getdefaulttimeout(), 10)
943 s = socket.socket()
944 self.assertEqual(s.gettimeout(), 10)
945 s.close()
946
947 # Reset the default timeout to None, and see if it propagates
948 socket.setdefaulttimeout(None)
949 self.assertEqual(socket.getdefaulttimeout(), None)
950 s = socket.socket()
951 self.assertEqual(s.gettimeout(), None)
952 s.close()
953
954 # Check that setting it to an invalid value raises ValueError
955 self.assertRaises(ValueError, socket.setdefaulttimeout, -1)
956
957 # Check that setting it to an invalid type raises TypeError
958 self.assertRaises(TypeError, socket.setdefaulttimeout, "spam")
959
Serhiy Storchaka43767632013-11-03 21:31:38 +0200960 @unittest.skipUnless(hasattr(socket, 'inet_aton'),
961 'test needs socket.inet_aton()')
Benjamin Petersonf91df042009-02-13 02:50:59 +0000962 def testIPv4_inet_aton_fourbytes(self):
Benjamin Petersonf91df042009-02-13 02:50:59 +0000963 # Test that issue1008086 and issue767150 are fixed.
964 # It must return 4 bytes.
Ezio Melottib3aedd42010-11-20 19:04:17 +0000965 self.assertEqual(b'\x00'*4, socket.inet_aton('0.0.0.0'))
966 self.assertEqual(b'\xff'*4, socket.inet_aton('255.255.255.255'))
Benjamin Petersonf91df042009-02-13 02:50:59 +0000967
Serhiy Storchaka43767632013-11-03 21:31:38 +0200968 @unittest.skipUnless(hasattr(socket, 'inet_pton'),
969 'test needs socket.inet_pton()')
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000970 def testIPv4toString(self):
971 from socket import inet_aton as f, inet_pton, AF_INET
972 g = lambda a: inet_pton(AF_INET, a)
973
Antoine Pitrou7ded21e2011-12-19 16:21:21 +0100974 assertInvalid = lambda func,a: self.assertRaises(
Andrew Svetlov0832af62012-12-18 23:10:48 +0200975 (OSError, ValueError), func, a
Antoine Pitrou7ded21e2011-12-19 16:21:21 +0100976 )
977
Ezio Melottib3aedd42010-11-20 19:04:17 +0000978 self.assertEqual(b'\x00\x00\x00\x00', f('0.0.0.0'))
979 self.assertEqual(b'\xff\x00\xff\x00', f('255.0.255.0'))
980 self.assertEqual(b'\xaa\xaa\xaa\xaa', f('170.170.170.170'))
981 self.assertEqual(b'\x01\x02\x03\x04', f('1.2.3.4'))
982 self.assertEqual(b'\xff\xff\xff\xff', f('255.255.255.255'))
Antoine Pitrou7ded21e2011-12-19 16:21:21 +0100983 assertInvalid(f, '0.0.0.')
984 assertInvalid(f, '300.0.0.0')
985 assertInvalid(f, 'a.0.0.0')
986 assertInvalid(f, '1.2.3.4.5')
987 assertInvalid(f, '::1')
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000988
Ezio Melottib3aedd42010-11-20 19:04:17 +0000989 self.assertEqual(b'\x00\x00\x00\x00', g('0.0.0.0'))
990 self.assertEqual(b'\xff\x00\xff\x00', g('255.0.255.0'))
991 self.assertEqual(b'\xaa\xaa\xaa\xaa', g('170.170.170.170'))
992 self.assertEqual(b'\xff\xff\xff\xff', g('255.255.255.255'))
Antoine Pitrou7ded21e2011-12-19 16:21:21 +0100993 assertInvalid(g, '0.0.0.')
994 assertInvalid(g, '300.0.0.0')
995 assertInvalid(g, 'a.0.0.0')
996 assertInvalid(g, '1.2.3.4.5')
997 assertInvalid(g, '::1')
Tim Petersc2659cf2003-05-12 20:19:37 +0000998
Serhiy Storchaka43767632013-11-03 21:31:38 +0200999 @unittest.skipUnless(hasattr(socket, 'inet_pton'),
1000 'test needs socket.inet_pton()')
Guido van Rossum47dfa4a2003-04-25 05:48:32 +00001001 def testIPv6toString(self):
1002 try:
1003 from socket import inet_pton, AF_INET6, has_ipv6
1004 if not has_ipv6:
Zachary Ware9fe6d862013-12-08 00:20:35 -06001005 self.skipTest('IPv6 not available')
Guido van Rossum47dfa4a2003-04-25 05:48:32 +00001006 except ImportError:
Zachary Ware9fe6d862013-12-08 00:20:35 -06001007 self.skipTest('could not import needed symbols from socket')
Jason R. Coombs6bdc4982013-11-10 14:02:04 -05001008
Atsuo Ishimotoda0fc142012-07-16 15:16:54 +09001009 if sys.platform == "win32":
1010 try:
1011 inet_pton(AF_INET6, '::')
1012 except OSError as e:
1013 if e.winerror == 10022:
Zachary Ware101d9e72013-12-08 00:44:27 -06001014 self.skipTest('IPv6 might not be supported')
Jason R. Coombs6bdc4982013-11-10 14:02:04 -05001015
Guido van Rossum47dfa4a2003-04-25 05:48:32 +00001016 f = lambda a: inet_pton(AF_INET6, a)
Antoine Pitrou7ded21e2011-12-19 16:21:21 +01001017 assertInvalid = lambda a: self.assertRaises(
Andrew Svetlov0832af62012-12-18 23:10:48 +02001018 (OSError, ValueError), f, a
Antoine Pitrou7ded21e2011-12-19 16:21:21 +01001019 )
Guido van Rossum47dfa4a2003-04-25 05:48:32 +00001020
Ezio Melottib3aedd42010-11-20 19:04:17 +00001021 self.assertEqual(b'\x00' * 16, f('::'))
1022 self.assertEqual(b'\x00' * 16, f('0::0'))
1023 self.assertEqual(b'\x00\x01' + b'\x00' * 14, f('1::'))
1024 self.assertEqual(
Guido van Rossum67180622007-07-10 07:29:12 +00001025 b'\x45\xef\x76\xcb\x00\x1a\x56\xef\xaf\xeb\x0b\xac\x19\x24\xae\xae',
Guido van Rossum47dfa4a2003-04-25 05:48:32 +00001026 f('45ef:76cb:1a:56ef:afeb:bac:1924:aeae')
1027 )
Antoine Pitrou7ded21e2011-12-19 16:21:21 +01001028 self.assertEqual(
1029 b'\xad\x42\x0a\xbc' + b'\x00' * 4 + b'\x01\x27\x00\x00\x02\x54\x00\x02',
1030 f('ad42:abc::127:0:254:2')
1031 )
1032 self.assertEqual(b'\x00\x12\x00\x0a' + b'\x00' * 12, f('12:a::'))
1033 assertInvalid('0x20::')
1034 assertInvalid(':::')
1035 assertInvalid('::0::')
1036 assertInvalid('1::abc::')
1037 assertInvalid('1::abc::def')
1038 assertInvalid('1:2:3:4:5:6:')
1039 assertInvalid('1:2:3:4:5:6')
1040 assertInvalid('1:2:3:4:5:6:7:8:')
1041 assertInvalid('1:2:3:4:5:6:7:8:0')
1042
1043 self.assertEqual(b'\x00' * 12 + b'\xfe\x2a\x17\x40',
1044 f('::254.42.23.64')
1045 )
1046 self.assertEqual(
1047 b'\x00\x42' + b'\x00' * 8 + b'\xa2\x9b\xfe\x2a\x17\x40',
1048 f('42::a29b:254.42.23.64')
1049 )
1050 self.assertEqual(
1051 b'\x00\x42\xa8\xb9\x00\x00\x00\x02\xff\xff\xa2\x9b\xfe\x2a\x17\x40',
1052 f('42:a8b9:0:2:ffff:a29b:254.42.23.64')
1053 )
1054 assertInvalid('255.254.253.252')
1055 assertInvalid('1::260.2.3.0')
1056 assertInvalid('1::0.be.e.0')
1057 assertInvalid('1:2:3:4:5:6:7:1.2.3.4')
1058 assertInvalid('::1.2.3.4:0')
1059 assertInvalid('0.100.200.0:3:4:5:6:7:8')
Tim Petersc2659cf2003-05-12 20:19:37 +00001060
Serhiy Storchaka43767632013-11-03 21:31:38 +02001061 @unittest.skipUnless(hasattr(socket, 'inet_ntop'),
1062 'test needs socket.inet_ntop()')
Guido van Rossum47dfa4a2003-04-25 05:48:32 +00001063 def testStringToIPv4(self):
1064 from socket import inet_ntoa as f, inet_ntop, AF_INET
1065 g = lambda a: inet_ntop(AF_INET, a)
Antoine Pitrou7ded21e2011-12-19 16:21:21 +01001066 assertInvalid = lambda func,a: self.assertRaises(
Andrew Svetlov0832af62012-12-18 23:10:48 +02001067 (OSError, ValueError), func, a
Antoine Pitrou7ded21e2011-12-19 16:21:21 +01001068 )
Guido van Rossum47dfa4a2003-04-25 05:48:32 +00001069
Ezio Melottib3aedd42010-11-20 19:04:17 +00001070 self.assertEqual('1.0.1.0', f(b'\x01\x00\x01\x00'))
1071 self.assertEqual('170.85.170.85', f(b'\xaa\x55\xaa\x55'))
1072 self.assertEqual('255.255.255.255', f(b'\xff\xff\xff\xff'))
1073 self.assertEqual('1.2.3.4', f(b'\x01\x02\x03\x04'))
Antoine Pitrou7ded21e2011-12-19 16:21:21 +01001074 assertInvalid(f, b'\x00' * 3)
1075 assertInvalid(f, b'\x00' * 5)
1076 assertInvalid(f, b'\x00' * 16)
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02001077 self.assertEqual('170.85.170.85', f(bytearray(b'\xaa\x55\xaa\x55')))
Tim Petersc2659cf2003-05-12 20:19:37 +00001078
Ezio Melottib3aedd42010-11-20 19:04:17 +00001079 self.assertEqual('1.0.1.0', g(b'\x01\x00\x01\x00'))
1080 self.assertEqual('170.85.170.85', g(b'\xaa\x55\xaa\x55'))
1081 self.assertEqual('255.255.255.255', g(b'\xff\xff\xff\xff'))
Antoine Pitrou7ded21e2011-12-19 16:21:21 +01001082 assertInvalid(g, b'\x00' * 3)
1083 assertInvalid(g, b'\x00' * 5)
1084 assertInvalid(g, b'\x00' * 16)
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02001085 self.assertEqual('170.85.170.85', g(bytearray(b'\xaa\x55\xaa\x55')))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +00001086
Serhiy Storchaka43767632013-11-03 21:31:38 +02001087 @unittest.skipUnless(hasattr(socket, 'inet_ntop'),
1088 'test needs socket.inet_ntop()')
Guido van Rossum47dfa4a2003-04-25 05:48:32 +00001089 def testStringToIPv6(self):
1090 try:
1091 from socket import inet_ntop, AF_INET6, has_ipv6
1092 if not has_ipv6:
Zachary Ware9fe6d862013-12-08 00:20:35 -06001093 self.skipTest('IPv6 not available')
Guido van Rossum47dfa4a2003-04-25 05:48:32 +00001094 except ImportError:
Zachary Ware9fe6d862013-12-08 00:20:35 -06001095 self.skipTest('could not import needed symbols from socket')
Atsuo Ishimotoda0fc142012-07-16 15:16:54 +09001096
1097 if sys.platform == "win32":
1098 try:
1099 inet_ntop(AF_INET6, b'\x00' * 16)
1100 except OSError as e:
1101 if e.winerror == 10022:
Zachary Ware101d9e72013-12-08 00:44:27 -06001102 self.skipTest('IPv6 might not be supported')
Atsuo Ishimotoda0fc142012-07-16 15:16:54 +09001103
Guido van Rossum47dfa4a2003-04-25 05:48:32 +00001104 f = lambda a: inet_ntop(AF_INET6, a)
Antoine Pitrou7ded21e2011-12-19 16:21:21 +01001105 assertInvalid = lambda a: self.assertRaises(
Andrew Svetlov0832af62012-12-18 23:10:48 +02001106 (OSError, ValueError), f, a
Antoine Pitrou7ded21e2011-12-19 16:21:21 +01001107 )
Guido van Rossum47dfa4a2003-04-25 05:48:32 +00001108
Ezio Melottib3aedd42010-11-20 19:04:17 +00001109 self.assertEqual('::', f(b'\x00' * 16))
1110 self.assertEqual('::1', f(b'\x00' * 15 + b'\x01'))
1111 self.assertEqual(
Guido van Rossum47dfa4a2003-04-25 05:48:32 +00001112 'aef:b01:506:1001:ffff:9997:55:170',
Guido van Rossum67180622007-07-10 07:29:12 +00001113 f(b'\x0a\xef\x0b\x01\x05\x06\x10\x01\xff\xff\x99\x97\x00\x55\x01\x70')
Guido van Rossum47dfa4a2003-04-25 05:48:32 +00001114 )
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02001115 self.assertEqual('::1', f(bytearray(b'\x00' * 15 + b'\x01')))
Guido van Rossum47dfa4a2003-04-25 05:48:32 +00001116
Antoine Pitrou7ded21e2011-12-19 16:21:21 +01001117 assertInvalid(b'\x12' * 15)
1118 assertInvalid(b'\x12' * 17)
1119 assertInvalid(b'\x12' * 4)
1120
Guido van Rossumb6cc7d22002-07-19 12:46:46 +00001121 # XXX The following don't test module-level functionality...
Guido van Rossum9d0c8ce2002-07-18 17:08:35 +00001122
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001123 def testSockName(self):
1124 # Testing getsockname()
Antoine Pitrouccc87b52011-05-10 23:37:11 +02001125 port = support.find_unused_port()
Guido van Rossum24e4af82002-06-12 19:18:08 +00001126 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Brian Curtin21ebbb72010-11-02 02:07:09 +00001127 self.addCleanup(sock.close)
Christian Heimes5e696852008-04-09 08:37:03 +00001128 sock.bind(("0.0.0.0", port))
Guido van Rossum24e4af82002-06-12 19:18:08 +00001129 name = sock.getsockname()
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001130 # XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate
1131 # it reasonable to get the host's addr in addition to 0.0.0.0.
1132 # At least for eCos. This is required for the S/390 to pass.
Georg Brandl89197fe2010-11-20 14:16:17 +00001133 try:
1134 my_ip_addr = socket.gethostbyname(socket.gethostname())
Andrew Svetlov0832af62012-12-18 23:10:48 +02001135 except OSError:
Georg Brandl89197fe2010-11-20 14:16:17 +00001136 # Probably name lookup wasn't set up right; skip this test
Zachary Ware9fe6d862013-12-08 00:20:35 -06001137 self.skipTest('name lookup failure')
Benjamin Peterson577473f2010-01-19 00:09:57 +00001138 self.assertIn(name[0], ("0.0.0.0", my_ip_addr), '%s invalid' % name[0])
Christian Heimes5e696852008-04-09 08:37:03 +00001139 self.assertEqual(name[1], port)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001140
1141 def testGetSockOpt(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00001142 # Testing getsockopt()
Guido van Rossum24e4af82002-06-12 19:18:08 +00001143 # We know a socket should start without reuse==0
1144 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Brian Curtin21ebbb72010-11-02 02:07:09 +00001145 self.addCleanup(sock.close)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001146 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001147 self.assertFalse(reuse != 0, "initial mode is reuse")
Guido van Rossum24e4af82002-06-12 19:18:08 +00001148
1149 def testSetSockOpt(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00001150 # Testing setsockopt()
Guido van Rossum24e4af82002-06-12 19:18:08 +00001151 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Brian Curtin21ebbb72010-11-02 02:07:09 +00001152 self.addCleanup(sock.close)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001153 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1154 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001155 self.assertFalse(reuse == 0, "failed to set reuse mode")
Guido van Rossum24e4af82002-06-12 19:18:08 +00001156
Guido van Rossumb6cc7d22002-07-19 12:46:46 +00001157 def testSendAfterClose(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00001158 # testing send() after close() with timeout
Guido van Rossumb6cc7d22002-07-19 12:46:46 +00001159 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1160 sock.settimeout(1)
1161 sock.close()
Andrew Svetlov0832af62012-12-18 23:10:48 +02001162 self.assertRaises(OSError, sock.send, b"spam")
Guido van Rossumb6cc7d22002-07-19 12:46:46 +00001163
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001164 def testNewAttributes(self):
1165 # testing .family, .type and .protocol
Victor Stinnerdaf45552013-08-28 00:53:59 +02001166
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001167 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1168 self.assertEqual(sock.family, socket.AF_INET)
Victor Stinnerdaf45552013-08-28 00:53:59 +02001169 if hasattr(socket, 'SOCK_CLOEXEC'):
1170 self.assertIn(sock.type,
1171 (socket.SOCK_STREAM | socket.SOCK_CLOEXEC,
1172 socket.SOCK_STREAM))
1173 else:
1174 self.assertEqual(sock.type, socket.SOCK_STREAM)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001175 self.assertEqual(sock.proto, 0)
1176 sock.close()
1177
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001178 def test_getsockaddrarg(self):
Charles-François Natali65708cf2014-07-25 18:44:30 +01001179 sock = socket.socket()
1180 self.addCleanup(sock.close)
Antoine Pitrouccc87b52011-05-10 23:37:11 +02001181 port = support.find_unused_port()
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001182 big_port = port + 65536
1183 neg_port = port - 65536
Charles-François Natali65708cf2014-07-25 18:44:30 +01001184 self.assertRaises(OverflowError, sock.bind, (HOST, big_port))
1185 self.assertRaises(OverflowError, sock.bind, (HOST, neg_port))
1186 # Since find_unused_port() is inherently subject to race conditions, we
1187 # call it a couple times if necessary.
1188 for i in itertools.count():
1189 port = support.find_unused_port()
1190 try:
1191 sock.bind((HOST, port))
1192 except OSError as e:
1193 if e.errno != errno.EADDRINUSE or i == 5:
1194 raise
1195 else:
1196 break
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001197
Brian Curtin5ad0bd62010-11-05 15:47:45 +00001198 @unittest.skipUnless(os.name == "nt", "Windows specific")
Christian Heimesfaf2f632008-01-06 16:59:19 +00001199 def test_sock_ioctl(self):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001200 self.assertTrue(hasattr(socket.socket, 'ioctl'))
1201 self.assertTrue(hasattr(socket, 'SIO_RCVALL'))
1202 self.assertTrue(hasattr(socket, 'RCVALL_ON'))
1203 self.assertTrue(hasattr(socket, 'RCVALL_OFF'))
Kristján Valur Jónsson847ec752009-09-27 21:10:38 +00001204 self.assertTrue(hasattr(socket, 'SIO_KEEPALIVE_VALS'))
1205 s = socket.socket()
Brian Curtin5ad0bd62010-11-05 15:47:45 +00001206 self.addCleanup(s.close)
Kristján Valur Jónsson847ec752009-09-27 21:10:38 +00001207 self.assertRaises(ValueError, s.ioctl, -1, None)
1208 s.ioctl(socket.SIO_KEEPALIVE_VALS, (1, 100, 100))
Christian Heimesfaf2f632008-01-06 16:59:19 +00001209
Giampaolo Rodolà419f7042010-08-14 16:45:41 +00001210 def testGetaddrinfo(self):
1211 try:
1212 socket.getaddrinfo('localhost', 80)
1213 except socket.gaierror as err:
1214 if err.errno == socket.EAI_SERVICE:
1215 # see http://bugs.python.org/issue1282647
1216 self.skipTest("buggy libc version")
1217 raise
1218 # len of every sequence is supposed to be == 5
1219 for info in socket.getaddrinfo(HOST, None):
1220 self.assertEqual(len(info), 5)
1221 # host can be a domain name, a string representation of an
1222 # IPv4/v6 address or None
1223 socket.getaddrinfo('localhost', 80)
1224 socket.getaddrinfo('127.0.0.1', 80)
1225 socket.getaddrinfo(None, 80)
Antoine Pitrou9c39f3c2011-04-28 19:18:10 +02001226 if support.IPV6_ENABLED:
Giampaolo Rodolà419f7042010-08-14 16:45:41 +00001227 socket.getaddrinfo('::1', 80)
1228 # port can be a string service name such as "http", a numeric
1229 # port number or None
1230 socket.getaddrinfo(HOST, "http")
1231 socket.getaddrinfo(HOST, 80)
1232 socket.getaddrinfo(HOST, None)
1233 # test family and socktype filters
Eli Benderskyb2ff3cf2013-08-31 15:13:30 -07001234 infos = socket.getaddrinfo(HOST, 80, socket.AF_INET, socket.SOCK_STREAM)
1235 for family, type, _, _, _ in infos:
Giampaolo Rodolà419f7042010-08-14 16:45:41 +00001236 self.assertEqual(family, socket.AF_INET)
Eli Benderskyb2ff3cf2013-08-31 15:13:30 -07001237 self.assertEqual(str(family), 'AddressFamily.AF_INET')
1238 self.assertEqual(type, socket.SOCK_STREAM)
Ethan Furman7184bac2014-10-14 18:56:53 -07001239 self.assertEqual(str(type), 'SocketKind.SOCK_STREAM')
Giampaolo Rodolà419f7042010-08-14 16:45:41 +00001240 infos = socket.getaddrinfo(HOST, None, 0, socket.SOCK_STREAM)
1241 for _, socktype, _, _, _ in infos:
1242 self.assertEqual(socktype, socket.SOCK_STREAM)
1243 # test proto and flags arguments
Giampaolo Rodolà677d95c2010-08-16 05:08:11 +00001244 socket.getaddrinfo(HOST, None, 0, 0, socket.SOL_TCP)
Giampaolo Rodolà419f7042010-08-14 16:45:41 +00001245 socket.getaddrinfo(HOST, None, 0, 0, 0, socket.AI_PASSIVE)
1246 # a server willing to support both IPv4 and IPv6 will
1247 # usually do this
1248 socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
1249 socket.AI_PASSIVE)
Giampaolo Rodolàccfb91c2010-08-17 15:30:23 +00001250 # test keyword arguments
1251 a = socket.getaddrinfo(HOST, None)
1252 b = socket.getaddrinfo(host=HOST, port=None)
1253 self.assertEqual(a, b)
1254 a = socket.getaddrinfo(HOST, None, socket.AF_INET)
1255 b = socket.getaddrinfo(HOST, None, family=socket.AF_INET)
1256 self.assertEqual(a, b)
1257 a = socket.getaddrinfo(HOST, None, 0, socket.SOCK_STREAM)
1258 b = socket.getaddrinfo(HOST, None, type=socket.SOCK_STREAM)
1259 self.assertEqual(a, b)
1260 a = socket.getaddrinfo(HOST, None, 0, 0, socket.SOL_TCP)
1261 b = socket.getaddrinfo(HOST, None, proto=socket.SOL_TCP)
1262 self.assertEqual(a, b)
1263 a = socket.getaddrinfo(HOST, None, 0, 0, 0, socket.AI_PASSIVE)
1264 b = socket.getaddrinfo(HOST, None, flags=socket.AI_PASSIVE)
1265 self.assertEqual(a, b)
1266 a = socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
1267 socket.AI_PASSIVE)
1268 b = socket.getaddrinfo(host=None, port=0, family=socket.AF_UNSPEC,
1269 type=socket.SOCK_STREAM, proto=0,
1270 flags=socket.AI_PASSIVE)
1271 self.assertEqual(a, b)
Alexander Belopolskye239d232010-12-08 23:31:48 +00001272 # Issue #6697.
1273 self.assertRaises(UnicodeEncodeError, socket.getaddrinfo, 'localhost', '\uD800')
Giampaolo Rodolà419f7042010-08-14 16:45:41 +00001274
Ned Deilyb24f4812014-02-13 22:50:42 -08001275 # Issue 17269: test workaround for OS X platform bug segfault
Ronald Oussorena822d3662013-06-10 10:36:28 +02001276 if hasattr(socket, 'AI_NUMERICSERV'):
Ned Deilyb24f4812014-02-13 22:50:42 -08001277 try:
1278 # The arguments here are undefined and the call may succeed
1279 # or fail. All we care here is that it doesn't segfault.
1280 socket.getaddrinfo("localhost", None, 0, 0, 0,
1281 socket.AI_NUMERICSERV)
1282 except socket.gaierror:
1283 pass
Ronald Oussoren27a4ac52013-05-24 13:47:37 +02001284
Martin v. Löwis112c0f32010-08-25 07:38:15 +00001285 def test_getnameinfo(self):
1286 # only IP addresses are allowed
Andrew Svetlov0832af62012-12-18 23:10:48 +02001287 self.assertRaises(OSError, socket.getnameinfo, ('mail.python.org',0), 0)
Martin v. Löwis112c0f32010-08-25 07:38:15 +00001288
Daniel Stutzbach460ff3d2010-09-09 21:17:58 +00001289 @unittest.skipUnless(support.is_resource_enabled('network'),
1290 'network is not enabled')
Martin v. Löwisfc0275a2010-08-22 19:33:47 +00001291 def test_idna(self):
Victor Stinner808d6412015-09-21 09:04:01 +02001292 # Check for internet access before running test
1293 # (issue #12804, issue #25138).
1294 with support.transient_internet('python.org'):
Nadeem Vawda61baebd2012-01-25 08:02:05 +02001295 socket.gethostbyname('python.org')
Victor Stinner808d6412015-09-21 09:04:01 +02001296
Martin v. Löwisfc0275a2010-08-22 19:33:47 +00001297 # these should all be successful
Benjamin Peterson863c9622014-11-03 15:10:47 -05001298 domain = 'испытание.pythontest.net'
1299 socket.gethostbyname(domain)
1300 socket.gethostbyname_ex(domain)
1301 socket.getaddrinfo(domain,0,socket.AF_UNSPEC,socket.SOCK_STREAM)
Martin v. Löwis67e91ad2010-08-23 15:27:26 +00001302 # this may not work if the forward lookup choses the IPv6 address, as that doesn't
1303 # have a reverse entry yet
1304 # socket.gethostbyaddr('испытание.python.org')
Christian Heimesfaf2f632008-01-06 16:59:19 +00001305
Antoine Pitrou6d7df632010-09-27 17:52:25 +00001306 def check_sendall_interrupted(self, with_timeout):
1307 # socketpair() is not stricly required, but it makes things easier.
1308 if not hasattr(signal, 'alarm') or not hasattr(socket, 'socketpair'):
1309 self.skipTest("signal.alarm and socket.socketpair required for this test")
1310 # Our signal handlers clobber the C errno by calling a math function
1311 # with an invalid domain value.
1312 def ok_handler(*args):
1313 self.assertRaises(ValueError, math.acosh, 0)
1314 def raising_handler(*args):
1315 self.assertRaises(ValueError, math.acosh, 0)
1316 1 // 0
1317 c, s = socket.socketpair()
1318 old_alarm = signal.signal(signal.SIGALRM, raising_handler)
1319 try:
1320 if with_timeout:
1321 # Just above the one second minimum for signal.alarm
1322 c.settimeout(1.5)
1323 with self.assertRaises(ZeroDivisionError):
1324 signal.alarm(1)
Charles-François Natali5fd26422013-08-29 19:01:40 +02001325 c.sendall(b"x" * support.SOCK_MAX_SIZE)
Antoine Pitrou6d7df632010-09-27 17:52:25 +00001326 if with_timeout:
1327 signal.signal(signal.SIGALRM, ok_handler)
1328 signal.alarm(1)
Charles-François Natali5fd26422013-08-29 19:01:40 +02001329 self.assertRaises(socket.timeout, c.sendall,
1330 b"x" * support.SOCK_MAX_SIZE)
Antoine Pitrou6d7df632010-09-27 17:52:25 +00001331 finally:
Victor Stinner71fe8c02013-08-24 15:52:47 +02001332 signal.alarm(0)
Antoine Pitrou6d7df632010-09-27 17:52:25 +00001333 signal.signal(signal.SIGALRM, old_alarm)
1334 c.close()
1335 s.close()
1336
1337 def test_sendall_interrupted(self):
1338 self.check_sendall_interrupted(False)
1339
1340 def test_sendall_interrupted_with_timeout(self):
1341 self.check_sendall_interrupted(True)
1342
Antoine Pitroue033e062010-10-29 10:38:18 +00001343 def test_dealloc_warn(self):
1344 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1345 r = repr(sock)
1346 with self.assertWarns(ResourceWarning) as cm:
1347 sock = None
1348 support.gc_collect()
1349 self.assertIn(r, str(cm.warning.args[0]))
1350 # An open socket file object gets dereferenced after the socket
1351 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1352 f = sock.makefile('rb')
1353 r = repr(sock)
1354 sock = None
1355 support.gc_collect()
1356 with self.assertWarns(ResourceWarning):
1357 f = None
1358 support.gc_collect()
1359
Victor Stinnerc3a51ec2011-01-04 11:00:45 +00001360 def test_name_closed_socketio(self):
1361 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
1362 fp = sock.makefile("rb")
1363 fp.close()
1364 self.assertEqual(repr(fp), "<_io.BufferedReader name=-1>")
1365
Antoine Pitrou1e7ee9d2012-09-14 17:28:10 +02001366 def test_unusable_closed_socketio(self):
1367 with socket.socket() as sock:
1368 fp = sock.makefile("rb", buffering=0)
1369 self.assertTrue(fp.readable())
1370 self.assertFalse(fp.writable())
1371 self.assertFalse(fp.seekable())
1372 fp.close()
1373 self.assertRaises(ValueError, fp.readable)
1374 self.assertRaises(ValueError, fp.writable)
1375 self.assertRaises(ValueError, fp.seekable)
1376
Antoine Pitrou6d58d642011-03-20 23:56:36 +01001377 def test_pickle(self):
1378 sock = socket.socket()
1379 with sock:
1380 for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
1381 self.assertRaises(TypeError, pickle.dumps, sock, protocol)
Ethan Furman24e837f2015-03-18 17:27:57 -07001382 for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
1383 family = pickle.loads(pickle.dumps(socket.AF_INET, protocol))
1384 self.assertEqual(family, socket.AF_INET)
1385 type = pickle.loads(pickle.dumps(socket.SOCK_STREAM, protocol))
1386 self.assertEqual(type, socket.SOCK_STREAM)
Antoine Pitrou6d58d642011-03-20 23:56:36 +01001387
Serhiy Storchaka78980432013-01-15 01:12:17 +02001388 def test_listen_backlog(self):
1389 for backlog in 0, -1:
Charles-François Natali644b8f52014-05-22 19:45:39 +01001390 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as srv:
1391 srv.bind((HOST, 0))
1392 srv.listen(backlog)
1393
1394 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as srv:
Serhiy Storchaka78980432013-01-15 01:12:17 +02001395 srv.bind((HOST, 0))
Charles-François Natali644b8f52014-05-22 19:45:39 +01001396 srv.listen()
Serhiy Storchaka78980432013-01-15 01:12:17 +02001397
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001398 @support.cpython_only
1399 def test_listen_backlog_overflow(self):
Serhiy Storchaka78980432013-01-15 01:12:17 +02001400 # Issue 15989
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001401 import _testcapi
Antoine Pitrou1be815a2011-05-10 19:16:29 +02001402 srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1403 srv.bind((HOST, 0))
Serhiy Storchaka78980432013-01-15 01:12:17 +02001404 self.assertRaises(OverflowError, srv.listen, _testcapi.INT_MAX + 1)
Antoine Pitrou1be815a2011-05-10 19:16:29 +02001405 srv.close()
1406
Charles-François Natali42663332012-01-02 15:57:30 +01001407 @unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.')
Charles-François Natali366999a2012-01-02 15:47:29 +01001408 def test_flowinfo(self):
1409 self.assertRaises(OverflowError, socket.getnameinfo,
Charles-François Natalifcfb3242013-08-31 14:40:49 +02001410 (support.HOSTv6, 0, 0xffffffff), 0)
Charles-François Natali366999a2012-01-02 15:47:29 +01001411 with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s:
Charles-François Natalifcfb3242013-08-31 14:40:49 +02001412 self.assertRaises(OverflowError, s.bind, (support.HOSTv6, 0, -10))
Charles-François Natali366999a2012-01-02 15:47:29 +01001413
Eli Benderskyb2ff3cf2013-08-31 15:13:30 -07001414 def test_str_for_enums(self):
1415 # Make sure that the AF_* and SOCK_* constants have enum-like string
1416 # reprs.
1417 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
1418 self.assertEqual(str(s.family), 'AddressFamily.AF_INET')
Ethan Furman7184bac2014-10-14 18:56:53 -07001419 self.assertEqual(str(s.type), 'SocketKind.SOCK_STREAM')
Eli Benderskyb2ff3cf2013-08-31 15:13:30 -07001420
1421 @unittest.skipIf(os.name == 'nt', 'Will not work on Windows')
1422 def test_uknown_socket_family_repr(self):
1423 # Test that when created with a family that's not one of the known
1424 # AF_*/SOCK_* constants, socket.family just returns the number.
1425 #
1426 # To do this we fool socket.socket into believing it already has an
1427 # open fd because on this path it doesn't actually verify the family and
1428 # type and populates the socket object.
1429 #
1430 # On Windows this trick won't work, so the test is skipped.
1431 fd, _ = tempfile.mkstemp()
1432 with socket.socket(family=42424, type=13331, fileno=fd) as s:
1433 self.assertEqual(s.family, 42424)
1434 self.assertEqual(s.type, 13331)
Antoine Pitrou6d7df632010-09-27 17:52:25 +00001435
Charles-François Natali47413c12011-10-06 19:47:44 +02001436@unittest.skipUnless(HAVE_SOCKET_CAN, 'SocketCan required for this test.')
1437class BasicCANTest(unittest.TestCase):
1438
1439 def testCrucialConstants(self):
1440 socket.AF_CAN
1441 socket.PF_CAN
1442 socket.CAN_RAW
1443
Charles-François Natali773e42d2013-02-05 19:42:01 +01001444 @unittest.skipUnless(hasattr(socket, "CAN_BCM"),
1445 'socket.CAN_BCM required for this test.')
1446 def testBCMConstants(self):
1447 socket.CAN_BCM
1448
1449 # opcodes
1450 socket.CAN_BCM_TX_SETUP # create (cyclic) transmission task
1451 socket.CAN_BCM_TX_DELETE # remove (cyclic) transmission task
1452 socket.CAN_BCM_TX_READ # read properties of (cyclic) transmission task
1453 socket.CAN_BCM_TX_SEND # send one CAN frame
1454 socket.CAN_BCM_RX_SETUP # create RX content filter subscription
1455 socket.CAN_BCM_RX_DELETE # remove RX content filter subscription
1456 socket.CAN_BCM_RX_READ # read properties of RX content filter subscription
1457 socket.CAN_BCM_TX_STATUS # reply to TX_READ request
1458 socket.CAN_BCM_TX_EXPIRED # notification on performed transmissions (count=0)
1459 socket.CAN_BCM_RX_STATUS # reply to RX_READ request
1460 socket.CAN_BCM_RX_TIMEOUT # cyclic message is absent
1461 socket.CAN_BCM_RX_CHANGED # updated CAN frame (detected content change)
1462
Charles-François Natali47413c12011-10-06 19:47:44 +02001463 def testCreateSocket(self):
1464 with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
1465 pass
1466
Charles-François Natali773e42d2013-02-05 19:42:01 +01001467 @unittest.skipUnless(hasattr(socket, "CAN_BCM"),
1468 'socket.CAN_BCM required for this test.')
1469 def testCreateBCMSocket(self):
1470 with socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_BCM) as s:
1471 pass
1472
Charles-François Natali47413c12011-10-06 19:47:44 +02001473 def testBindAny(self):
1474 with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
1475 s.bind(('', ))
1476
1477 def testTooLongInterfaceName(self):
1478 # most systems limit IFNAMSIZ to 16, take 1024 to be sure
1479 with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
Andrew Svetlov0832af62012-12-18 23:10:48 +02001480 self.assertRaisesRegex(OSError, 'interface name too long',
Antoine Pitrouffa547e2011-10-11 22:43:37 +02001481 s.bind, ('x' * 1024,))
Charles-François Natali47413c12011-10-06 19:47:44 +02001482
1483 @unittest.skipUnless(hasattr(socket, "CAN_RAW_LOOPBACK"),
1484 'socket.CAN_RAW_LOOPBACK required for this test.')
1485 def testLoopback(self):
1486 with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
1487 for loopback in (0, 1):
1488 s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_LOOPBACK,
1489 loopback)
1490 self.assertEqual(loopback,
1491 s.getsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_LOOPBACK))
1492
1493 @unittest.skipUnless(hasattr(socket, "CAN_RAW_FILTER"),
1494 'socket.CAN_RAW_FILTER required for this test.')
1495 def testFilter(self):
1496 can_id, can_mask = 0x200, 0x700
1497 can_filter = struct.pack("=II", can_id, can_mask)
1498 with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
1499 s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FILTER, can_filter)
1500 self.assertEqual(can_filter,
1501 s.getsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FILTER, 8))
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02001502 s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FILTER, bytearray(can_filter))
Charles-François Natali47413c12011-10-06 19:47:44 +02001503
1504
1505@unittest.skipUnless(HAVE_SOCKET_CAN, 'SocketCan required for this test.')
Terry Jan Reedya40e6b02014-06-13 15:20:45 -04001506@unittest.skipUnless(thread, 'Threading required for this test.')
Charles-François Natali47413c12011-10-06 19:47:44 +02001507class CANTest(ThreadedCANSocketTest):
1508
Charles-François Natali47413c12011-10-06 19:47:44 +02001509 def __init__(self, methodName='runTest'):
1510 ThreadedCANSocketTest.__init__(self, methodName=methodName)
1511
1512 @classmethod
1513 def build_can_frame(cls, can_id, data):
1514 """Build a CAN frame."""
1515 can_dlc = len(data)
1516 data = data.ljust(8, b'\x00')
1517 return struct.pack(cls.can_frame_fmt, can_id, can_dlc, data)
1518
1519 @classmethod
1520 def dissect_can_frame(cls, frame):
1521 """Dissect a CAN frame."""
1522 can_id, can_dlc, data = struct.unpack(cls.can_frame_fmt, frame)
1523 return (can_id, can_dlc, data[:can_dlc])
1524
1525 def testSendFrame(self):
1526 cf, addr = self.s.recvfrom(self.bufsize)
1527 self.assertEqual(self.cf, cf)
1528 self.assertEqual(addr[0], self.interface)
1529 self.assertEqual(addr[1], socket.AF_CAN)
1530
1531 def _testSendFrame(self):
1532 self.cf = self.build_can_frame(0x00, b'\x01\x02\x03\x04\x05')
1533 self.cli.send(self.cf)
1534
1535 def testSendMaxFrame(self):
1536 cf, addr = self.s.recvfrom(self.bufsize)
1537 self.assertEqual(self.cf, cf)
1538
1539 def _testSendMaxFrame(self):
1540 self.cf = self.build_can_frame(0x00, b'\x07' * 8)
1541 self.cli.send(self.cf)
1542
1543 def testSendMultiFrames(self):
1544 cf, addr = self.s.recvfrom(self.bufsize)
1545 self.assertEqual(self.cf1, cf)
1546
1547 cf, addr = self.s.recvfrom(self.bufsize)
1548 self.assertEqual(self.cf2, cf)
1549
1550 def _testSendMultiFrames(self):
1551 self.cf1 = self.build_can_frame(0x07, b'\x44\x33\x22\x11')
1552 self.cli.send(self.cf1)
1553
1554 self.cf2 = self.build_can_frame(0x12, b'\x99\x22\x33')
1555 self.cli.send(self.cf2)
1556
Charles-François Natali773e42d2013-02-05 19:42:01 +01001557 @unittest.skipUnless(hasattr(socket, "CAN_BCM"),
1558 'socket.CAN_BCM required for this test.')
1559 def _testBCM(self):
1560 cf, addr = self.cli.recvfrom(self.bufsize)
1561 self.assertEqual(self.cf, cf)
1562 can_id, can_dlc, data = self.dissect_can_frame(cf)
1563 self.assertEqual(self.can_id, can_id)
1564 self.assertEqual(self.data, data)
1565
1566 @unittest.skipUnless(hasattr(socket, "CAN_BCM"),
1567 'socket.CAN_BCM required for this test.')
1568 def testBCM(self):
1569 bcm = socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_BCM)
1570 self.addCleanup(bcm.close)
1571 bcm.connect((self.interface,))
1572 self.can_id = 0x123
1573 self.data = bytes([0xc0, 0xff, 0xee])
1574 self.cf = self.build_can_frame(self.can_id, self.data)
1575 opcode = socket.CAN_BCM_TX_SEND
1576 flags = 0
1577 count = 0
1578 ival1_seconds = ival1_usec = ival2_seconds = ival2_usec = 0
1579 bcm_can_id = 0x0222
1580 nframes = 1
1581 assert len(self.cf) == 16
1582 header = struct.pack(self.bcm_cmd_msg_fmt,
1583 opcode,
1584 flags,
1585 count,
1586 ival1_seconds,
1587 ival1_usec,
1588 ival2_seconds,
1589 ival2_usec,
1590 bcm_can_id,
1591 nframes,
1592 )
1593 header_plus_frame = header + self.cf
1594 bytes_sent = bcm.send(header_plus_frame)
1595 self.assertEqual(bytes_sent, len(header_plus_frame))
1596
Charles-François Natali47413c12011-10-06 19:47:44 +02001597
Charles-François Natali10b8cf42011-11-10 19:21:37 +01001598@unittest.skipUnless(HAVE_SOCKET_RDS, 'RDS sockets required for this test.')
1599class BasicRDSTest(unittest.TestCase):
1600
1601 def testCrucialConstants(self):
1602 socket.AF_RDS
1603 socket.PF_RDS
1604
1605 def testCreateSocket(self):
1606 with socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0) as s:
1607 pass
1608
1609 def testSocketBufferSize(self):
1610 bufsize = 16384
1611 with socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0) as s:
1612 s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, bufsize)
1613 s.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, bufsize)
1614
1615
1616@unittest.skipUnless(HAVE_SOCKET_RDS, 'RDS sockets required for this test.')
1617@unittest.skipUnless(thread, 'Threading required for this test.')
1618class RDSTest(ThreadedRDSSocketTest):
1619
1620 def __init__(self, methodName='runTest'):
1621 ThreadedRDSSocketTest.__init__(self, methodName=methodName)
1622
Charles-François Natali240c55f2011-11-10 20:33:36 +01001623 def setUp(self):
1624 super().setUp()
1625 self.evt = threading.Event()
1626
Charles-François Natali10b8cf42011-11-10 19:21:37 +01001627 def testSendAndRecv(self):
1628 data, addr = self.serv.recvfrom(self.bufsize)
1629 self.assertEqual(self.data, data)
1630 self.assertEqual(self.cli_addr, addr)
1631
1632 def _testSendAndRecv(self):
1633 self.data = b'spam'
1634 self.cli.sendto(self.data, 0, (HOST, self.port))
1635
1636 def testPeek(self):
1637 data, addr = self.serv.recvfrom(self.bufsize, socket.MSG_PEEK)
1638 self.assertEqual(self.data, data)
1639 data, addr = self.serv.recvfrom(self.bufsize)
1640 self.assertEqual(self.data, data)
1641
1642 def _testPeek(self):
1643 self.data = b'spam'
1644 self.cli.sendto(self.data, 0, (HOST, self.port))
1645
1646 @requireAttrs(socket.socket, 'recvmsg')
1647 def testSendAndRecvMsg(self):
1648 data, ancdata, msg_flags, addr = self.serv.recvmsg(self.bufsize)
1649 self.assertEqual(self.data, data)
1650
1651 @requireAttrs(socket.socket, 'sendmsg')
1652 def _testSendAndRecvMsg(self):
1653 self.data = b'hello ' * 10
1654 self.cli.sendmsg([self.data], (), 0, (HOST, self.port))
1655
1656 def testSendAndRecvMulti(self):
1657 data, addr = self.serv.recvfrom(self.bufsize)
1658 self.assertEqual(self.data1, data)
1659
1660 data, addr = self.serv.recvfrom(self.bufsize)
1661 self.assertEqual(self.data2, data)
1662
1663 def _testSendAndRecvMulti(self):
1664 self.data1 = b'bacon'
1665 self.cli.sendto(self.data1, 0, (HOST, self.port))
1666
1667 self.data2 = b'egg'
1668 self.cli.sendto(self.data2, 0, (HOST, self.port))
1669
1670 def testSelect(self):
1671 r, w, x = select.select([self.serv], [], [], 3.0)
1672 self.assertIn(self.serv, r)
1673 data, addr = self.serv.recvfrom(self.bufsize)
1674 self.assertEqual(self.data, data)
1675
1676 def _testSelect(self):
1677 self.data = b'select'
1678 self.cli.sendto(self.data, 0, (HOST, self.port))
1679
1680 def testCongestion(self):
1681 # wait until the sender is done
1682 self.evt.wait()
1683
1684 def _testCongestion(self):
1685 # test the behavior in case of congestion
1686 self.data = b'fill'
1687 self.cli.setblocking(False)
1688 try:
1689 # try to lower the receiver's socket buffer size
1690 self.cli.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 16384)
1691 except OSError:
1692 pass
1693 with self.assertRaises(OSError) as cm:
1694 try:
1695 # fill the receiver's socket buffer
1696 while True:
1697 self.cli.sendto(self.data, 0, (HOST, self.port))
1698 finally:
1699 # signal the receiver we're done
1700 self.evt.set()
1701 # sendto() should have failed with ENOBUFS
1702 self.assertEqual(cm.exception.errno, errno.ENOBUFS)
1703 # and we should have received a congestion notification through poll
1704 r, w, x = select.select([self.serv], [], [], 3.0)
1705 self.assertIn(self.serv, r)
1706
1707
Victor Stinner45df8202010-04-28 22:31:17 +00001708@unittest.skipUnless(thread, 'Threading required for this test.')
Guido van Rossum24e4af82002-06-12 19:18:08 +00001709class BasicTCPTest(SocketConnectedTest):
1710
1711 def __init__(self, methodName='runTest'):
1712 SocketConnectedTest.__init__(self, methodName=methodName)
1713
1714 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00001715 # Testing large receive over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +00001716 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +00001717 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001718
1719 def _testRecv(self):
1720 self.serv_conn.send(MSG)
1721
1722 def testOverFlowRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00001723 # Testing receive in chunks over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +00001724 seg1 = self.cli_conn.recv(len(MSG) - 3)
1725 seg2 = self.cli_conn.recv(1024)
Guido van Rossumab659962002-06-12 21:29:43 +00001726 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +00001727 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001728
1729 def _testOverFlowRecv(self):
1730 self.serv_conn.send(MSG)
1731
1732 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00001733 # Testing large recvfrom() over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +00001734 msg, addr = self.cli_conn.recvfrom(1024)
Guido van Rossum76489682002-06-12 20:38:30 +00001735 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001736
1737 def _testRecvFrom(self):
1738 self.serv_conn.send(MSG)
1739
1740 def testOverFlowRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00001741 # Testing recvfrom() in chunks over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +00001742 seg1, addr = self.cli_conn.recvfrom(len(MSG)-3)
1743 seg2, addr = self.cli_conn.recvfrom(1024)
Guido van Rossumab659962002-06-12 21:29:43 +00001744 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +00001745 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001746
1747 def _testOverFlowRecvFrom(self):
1748 self.serv_conn.send(MSG)
1749
1750 def testSendAll(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00001751 # Testing sendall() with a 2048 byte string over TCP
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001752 msg = b''
Guido van Rossum24e4af82002-06-12 19:18:08 +00001753 while 1:
1754 read = self.cli_conn.recv(1024)
1755 if not read:
1756 break
Guido van Rossume531e292002-08-08 20:28:34 +00001757 msg += read
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001758 self.assertEqual(msg, b'f' * 2048)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001759
1760 def _testSendAll(self):
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001761 big_chunk = b'f' * 2048
Guido van Rossum24e4af82002-06-12 19:18:08 +00001762 self.serv_conn.sendall(big_chunk)
1763
1764 def testFromFd(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00001765 # Testing fromfd()
Guido van Rossum24e4af82002-06-12 19:18:08 +00001766 fd = self.cli_conn.fileno()
1767 sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
Brian Curtin21ebbb72010-11-02 02:07:09 +00001768 self.addCleanup(sock.close)
Antoine Pitrou9e0b8642010-09-14 18:00:02 +00001769 self.assertIsInstance(sock, socket.socket)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001770 msg = sock.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +00001771 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001772
1773 def _testFromFd(self):
1774 self.serv_conn.send(MSG)
1775
Guido van Rossum39eb8fa2007-11-16 01:24:05 +00001776 def testDup(self):
1777 # Testing dup()
1778 sock = self.cli_conn.dup()
Brian Curtin21ebbb72010-11-02 02:07:09 +00001779 self.addCleanup(sock.close)
Guido van Rossum39eb8fa2007-11-16 01:24:05 +00001780 msg = sock.recv(1024)
1781 self.assertEqual(msg, MSG)
1782
1783 def _testDup(self):
1784 self.serv_conn.send(MSG)
1785
Guido van Rossum24e4af82002-06-12 19:18:08 +00001786 def testShutdown(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00001787 # Testing shutdown()
Guido van Rossum24e4af82002-06-12 19:18:08 +00001788 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +00001789 self.assertEqual(msg, MSG)
Mark Dickinson29500f62009-01-15 15:36:10 +00001790 # wait for _testShutdown to finish: on OS X, when the server
1791 # closes the connection the client also becomes disconnected,
1792 # and the client's shutdown call will fail. (Issue #4397.)
1793 self.done.wait()
Guido van Rossum24e4af82002-06-12 19:18:08 +00001794
1795 def _testShutdown(self):
1796 self.serv_conn.send(MSG)
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001797 self.serv_conn.shutdown(2)
1798
1799 testShutdown_overflow = support.cpython_only(testShutdown)
1800
1801 @support.cpython_only
1802 def _testShutdown_overflow(self):
1803 import _testcapi
1804 self.serv_conn.send(MSG)
Serhiy Storchaka78980432013-01-15 01:12:17 +02001805 # Issue 15989
1806 self.assertRaises(OverflowError, self.serv_conn.shutdown,
1807 _testcapi.INT_MAX + 1)
1808 self.assertRaises(OverflowError, self.serv_conn.shutdown,
1809 2 + (_testcapi.UINT_MAX + 1))
Guido van Rossum24e4af82002-06-12 19:18:08 +00001810 self.serv_conn.shutdown(2)
1811
Antoine Pitrou6e451df2010-08-09 20:39:54 +00001812 def testDetach(self):
1813 # Testing detach()
1814 fileno = self.cli_conn.fileno()
1815 f = self.cli_conn.detach()
1816 self.assertEqual(f, fileno)
1817 # cli_conn cannot be used anymore...
Antoine Pitrou70deb3d2012-04-01 01:00:17 +02001818 self.assertTrue(self.cli_conn._closed)
Andrew Svetlov0832af62012-12-18 23:10:48 +02001819 self.assertRaises(OSError, self.cli_conn.recv, 1024)
Antoine Pitroue43f9d02010-08-08 23:24:50 +00001820 self.cli_conn.close()
Antoine Pitrou6e451df2010-08-09 20:39:54 +00001821 # ...but we can create another socket using the (still open)
1822 # file descriptor
Antoine Pitroue43f9d02010-08-08 23:24:50 +00001823 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, fileno=f)
Brian Curtin21ebbb72010-11-02 02:07:09 +00001824 self.addCleanup(sock.close)
Antoine Pitroue43f9d02010-08-08 23:24:50 +00001825 msg = sock.recv(1024)
1826 self.assertEqual(msg, MSG)
1827
Antoine Pitrou6e451df2010-08-09 20:39:54 +00001828 def _testDetach(self):
Antoine Pitroue43f9d02010-08-08 23:24:50 +00001829 self.serv_conn.send(MSG)
1830
Victor Stinner45df8202010-04-28 22:31:17 +00001831@unittest.skipUnless(thread, 'Threading required for this test.')
Guido van Rossum24e4af82002-06-12 19:18:08 +00001832class BasicUDPTest(ThreadedUDPSocketTest):
1833
1834 def __init__(self, methodName='runTest'):
1835 ThreadedUDPSocketTest.__init__(self, methodName=methodName)
1836
1837 def testSendtoAndRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00001838 # Testing sendto() and Recv() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +00001839 msg = self.serv.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +00001840 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001841
1842 def _testSendtoAndRecv(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001843 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +00001844
Guido van Rossum1c938012002-06-12 21:17:20 +00001845 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00001846 # Testing recvfrom() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +00001847 msg, addr = self.serv.recvfrom(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +00001848 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001849
Guido van Rossum1c938012002-06-12 21:17:20 +00001850 def _testRecvFrom(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001851 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +00001852
Guido van Rossumd8faa362007-04-27 19:54:29 +00001853 def testRecvFromNegative(self):
1854 # Negative lengths passed to recvfrom should give ValueError.
1855 self.assertRaises(ValueError, self.serv.recvfrom, -1)
1856
1857 def _testRecvFromNegative(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001858 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001859
Nick Coghlan96fe56a2011-08-22 11:55:57 +10001860# Tests for the sendmsg()/recvmsg() interface. Where possible, the
1861# same test code is used with different families and types of socket
1862# (e.g. stream, datagram), and tests using recvmsg() are repeated
1863# using recvmsg_into().
1864#
1865# The generic test classes such as SendmsgTests and
1866# RecvmsgGenericTests inherit from SendrecvmsgBase and expect to be
1867# supplied with sockets cli_sock and serv_sock representing the
1868# client's and the server's end of the connection respectively, and
1869# attributes cli_addr and serv_addr holding their (numeric where
1870# appropriate) addresses.
1871#
1872# The final concrete test classes combine these with subclasses of
1873# SocketTestBase which set up client and server sockets of a specific
1874# type, and with subclasses of SendrecvmsgBase such as
1875# SendrecvmsgDgramBase and SendrecvmsgConnectedBase which map these
1876# sockets to cli_sock and serv_sock and override the methods and
1877# attributes of SendrecvmsgBase to fill in destination addresses if
1878# needed when sending, check for specific flags in msg_flags, etc.
1879#
1880# RecvmsgIntoMixin provides a version of doRecvmsg() implemented using
1881# recvmsg_into().
1882
1883# XXX: like the other datagram (UDP) tests in this module, the code
1884# here assumes that datagram delivery on the local machine will be
1885# reliable.
1886
1887class SendrecvmsgBase(ThreadSafeCleanupTestCase):
1888 # Base class for sendmsg()/recvmsg() tests.
1889
1890 # Time in seconds to wait before considering a test failed, or
1891 # None for no timeout. Not all tests actually set a timeout.
1892 fail_timeout = 3.0
1893
1894 def setUp(self):
1895 self.misc_event = threading.Event()
1896 super().setUp()
1897
1898 def sendToServer(self, msg):
1899 # Send msg to the server.
1900 return self.cli_sock.send(msg)
1901
1902 # Tuple of alternative default arguments for sendmsg() when called
1903 # via sendmsgToServer() (e.g. to include a destination address).
1904 sendmsg_to_server_defaults = ()
1905
1906 def sendmsgToServer(self, *args):
1907 # Call sendmsg() on self.cli_sock with the given arguments,
1908 # filling in any arguments which are not supplied with the
1909 # corresponding items of self.sendmsg_to_server_defaults, if
1910 # any.
1911 return self.cli_sock.sendmsg(
1912 *(args + self.sendmsg_to_server_defaults[len(args):]))
1913
1914 def doRecvmsg(self, sock, bufsize, *args):
1915 # Call recvmsg() on sock with given arguments and return its
1916 # result. Should be used for tests which can use either
1917 # recvmsg() or recvmsg_into() - RecvmsgIntoMixin overrides
1918 # this method with one which emulates it using recvmsg_into(),
1919 # thus allowing the same test to be used for both methods.
1920 result = sock.recvmsg(bufsize, *args)
1921 self.registerRecvmsgResult(result)
1922 return result
1923
1924 def registerRecvmsgResult(self, result):
1925 # Called by doRecvmsg() with the return value of recvmsg() or
1926 # recvmsg_into(). Can be overridden to arrange cleanup based
1927 # on the returned ancillary data, for instance.
1928 pass
1929
1930 def checkRecvmsgAddress(self, addr1, addr2):
1931 # Called to compare the received address with the address of
1932 # the peer.
1933 self.assertEqual(addr1, addr2)
1934
1935 # Flags that are normally unset in msg_flags
1936 msg_flags_common_unset = 0
1937 for name in ("MSG_CTRUNC", "MSG_OOB"):
1938 msg_flags_common_unset |= getattr(socket, name, 0)
1939
1940 # Flags that are normally set
1941 msg_flags_common_set = 0
1942
1943 # Flags set when a complete record has been received (e.g. MSG_EOR
1944 # for SCTP)
1945 msg_flags_eor_indicator = 0
1946
1947 # Flags set when a complete record has not been received
1948 # (e.g. MSG_TRUNC for datagram sockets)
1949 msg_flags_non_eor_indicator = 0
1950
1951 def checkFlags(self, flags, eor=None, checkset=0, checkunset=0, ignore=0):
1952 # Method to check the value of msg_flags returned by recvmsg[_into]().
1953 #
1954 # Checks that all bits in msg_flags_common_set attribute are
1955 # set in "flags" and all bits in msg_flags_common_unset are
1956 # unset.
1957 #
1958 # The "eor" argument specifies whether the flags should
1959 # indicate that a full record (or datagram) has been received.
1960 # If "eor" is None, no checks are done; otherwise, checks
1961 # that:
1962 #
1963 # * if "eor" is true, all bits in msg_flags_eor_indicator are
1964 # set and all bits in msg_flags_non_eor_indicator are unset
1965 #
1966 # * if "eor" is false, all bits in msg_flags_non_eor_indicator
1967 # are set and all bits in msg_flags_eor_indicator are unset
1968 #
1969 # If "checkset" and/or "checkunset" are supplied, they require
1970 # the given bits to be set or unset respectively, overriding
1971 # what the attributes require for those bits.
1972 #
1973 # If any bits are set in "ignore", they will not be checked,
1974 # regardless of the other inputs.
1975 #
1976 # Will raise Exception if the inputs require a bit to be both
1977 # set and unset, and it is not ignored.
1978
1979 defaultset = self.msg_flags_common_set
1980 defaultunset = self.msg_flags_common_unset
1981
1982 if eor:
1983 defaultset |= self.msg_flags_eor_indicator
1984 defaultunset |= self.msg_flags_non_eor_indicator
1985 elif eor is not None:
1986 defaultset |= self.msg_flags_non_eor_indicator
1987 defaultunset |= self.msg_flags_eor_indicator
1988
1989 # Function arguments override defaults
1990 defaultset &= ~checkunset
1991 defaultunset &= ~checkset
1992
1993 # Merge arguments with remaining defaults, and check for conflicts
1994 checkset |= defaultset
1995 checkunset |= defaultunset
1996 inboth = checkset & checkunset & ~ignore
1997 if inboth:
1998 raise Exception("contradictory set, unset requirements for flags "
1999 "{0:#x}".format(inboth))
2000
2001 # Compare with given msg_flags value
2002 mask = (checkset | checkunset) & ~ignore
2003 self.assertEqual(flags & mask, checkset & mask)
2004
2005
2006class RecvmsgIntoMixin(SendrecvmsgBase):
2007 # Mixin to implement doRecvmsg() using recvmsg_into().
2008
2009 def doRecvmsg(self, sock, bufsize, *args):
2010 buf = bytearray(bufsize)
2011 result = sock.recvmsg_into([buf], *args)
2012 self.registerRecvmsgResult(result)
2013 self.assertGreaterEqual(result[0], 0)
2014 self.assertLessEqual(result[0], bufsize)
2015 return (bytes(buf[:result[0]]),) + result[1:]
2016
2017
2018class SendrecvmsgDgramFlagsBase(SendrecvmsgBase):
2019 # Defines flags to be checked in msg_flags for datagram sockets.
2020
2021 @property
2022 def msg_flags_non_eor_indicator(self):
2023 return super().msg_flags_non_eor_indicator | socket.MSG_TRUNC
2024
2025
2026class SendrecvmsgSCTPFlagsBase(SendrecvmsgBase):
2027 # Defines flags to be checked in msg_flags for SCTP sockets.
2028
2029 @property
2030 def msg_flags_eor_indicator(self):
2031 return super().msg_flags_eor_indicator | socket.MSG_EOR
2032
2033
2034class SendrecvmsgConnectionlessBase(SendrecvmsgBase):
2035 # Base class for tests on connectionless-mode sockets. Users must
2036 # supply sockets on attributes cli and serv to be mapped to
2037 # cli_sock and serv_sock respectively.
2038
2039 @property
2040 def serv_sock(self):
2041 return self.serv
2042
2043 @property
2044 def cli_sock(self):
2045 return self.cli
2046
2047 @property
2048 def sendmsg_to_server_defaults(self):
2049 return ([], [], 0, self.serv_addr)
2050
2051 def sendToServer(self, msg):
2052 return self.cli_sock.sendto(msg, self.serv_addr)
2053
2054
2055class SendrecvmsgConnectedBase(SendrecvmsgBase):
2056 # Base class for tests on connected sockets. Users must supply
2057 # sockets on attributes serv_conn and cli_conn (representing the
2058 # connections *to* the server and the client), to be mapped to
2059 # cli_sock and serv_sock respectively.
2060
2061 @property
2062 def serv_sock(self):
2063 return self.cli_conn
2064
2065 @property
2066 def cli_sock(self):
2067 return self.serv_conn
2068
2069 def checkRecvmsgAddress(self, addr1, addr2):
2070 # Address is currently "unspecified" for a connected socket,
2071 # so we don't examine it
2072 pass
2073
2074
2075class SendrecvmsgServerTimeoutBase(SendrecvmsgBase):
2076 # Base class to set a timeout on server's socket.
2077
2078 def setUp(self):
2079 super().setUp()
2080 self.serv_sock.settimeout(self.fail_timeout)
2081
2082
2083class SendmsgTests(SendrecvmsgServerTimeoutBase):
2084 # Tests for sendmsg() which can use any socket type and do not
2085 # involve recvmsg() or recvmsg_into().
2086
2087 def testSendmsg(self):
2088 # Send a simple message with sendmsg().
2089 self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
2090
2091 def _testSendmsg(self):
2092 self.assertEqual(self.sendmsgToServer([MSG]), len(MSG))
2093
2094 def testSendmsgDataGenerator(self):
2095 # Send from buffer obtained from a generator (not a sequence).
2096 self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
2097
2098 def _testSendmsgDataGenerator(self):
2099 self.assertEqual(self.sendmsgToServer((o for o in [MSG])),
2100 len(MSG))
2101
2102 def testSendmsgAncillaryGenerator(self):
2103 # Gather (empty) ancillary data from a generator.
2104 self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
2105
2106 def _testSendmsgAncillaryGenerator(self):
2107 self.assertEqual(self.sendmsgToServer([MSG], (o for o in [])),
2108 len(MSG))
2109
2110 def testSendmsgArray(self):
2111 # Send data from an array instead of the usual bytes object.
2112 self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
2113
2114 def _testSendmsgArray(self):
2115 self.assertEqual(self.sendmsgToServer([array.array("B", MSG)]),
2116 len(MSG))
2117
2118 def testSendmsgGather(self):
2119 # Send message data from more than one buffer (gather write).
2120 self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
2121
2122 def _testSendmsgGather(self):
2123 self.assertEqual(self.sendmsgToServer([MSG[:3], MSG[3:]]), len(MSG))
2124
2125 def testSendmsgBadArgs(self):
2126 # Check that sendmsg() rejects invalid arguments.
2127 self.assertEqual(self.serv_sock.recv(1000), b"done")
2128
2129 def _testSendmsgBadArgs(self):
2130 self.assertRaises(TypeError, self.cli_sock.sendmsg)
2131 self.assertRaises(TypeError, self.sendmsgToServer,
2132 b"not in an iterable")
2133 self.assertRaises(TypeError, self.sendmsgToServer,
2134 object())
2135 self.assertRaises(TypeError, self.sendmsgToServer,
2136 [object()])
2137 self.assertRaises(TypeError, self.sendmsgToServer,
2138 [MSG, object()])
2139 self.assertRaises(TypeError, self.sendmsgToServer,
2140 [MSG], object())
2141 self.assertRaises(TypeError, self.sendmsgToServer,
2142 [MSG], [], object())
2143 self.assertRaises(TypeError, self.sendmsgToServer,
2144 [MSG], [], 0, object())
2145 self.sendToServer(b"done")
2146
2147 def testSendmsgBadCmsg(self):
2148 # Check that invalid ancillary data items are rejected.
2149 self.assertEqual(self.serv_sock.recv(1000), b"done")
2150
2151 def _testSendmsgBadCmsg(self):
2152 self.assertRaises(TypeError, self.sendmsgToServer,
2153 [MSG], [object()])
2154 self.assertRaises(TypeError, self.sendmsgToServer,
2155 [MSG], [(object(), 0, b"data")])
2156 self.assertRaises(TypeError, self.sendmsgToServer,
2157 [MSG], [(0, object(), b"data")])
2158 self.assertRaises(TypeError, self.sendmsgToServer,
2159 [MSG], [(0, 0, object())])
2160 self.assertRaises(TypeError, self.sendmsgToServer,
2161 [MSG], [(0, 0)])
2162 self.assertRaises(TypeError, self.sendmsgToServer,
2163 [MSG], [(0, 0, b"data", 42)])
2164 self.sendToServer(b"done")
2165
2166 @requireAttrs(socket, "CMSG_SPACE")
2167 def testSendmsgBadMultiCmsg(self):
2168 # Check that invalid ancillary data items are rejected when
2169 # more than one item is present.
2170 self.assertEqual(self.serv_sock.recv(1000), b"done")
2171
2172 @testSendmsgBadMultiCmsg.client_skip
2173 def _testSendmsgBadMultiCmsg(self):
2174 self.assertRaises(TypeError, self.sendmsgToServer,
2175 [MSG], [0, 0, b""])
2176 self.assertRaises(TypeError, self.sendmsgToServer,
2177 [MSG], [(0, 0, b""), object()])
2178 self.sendToServer(b"done")
2179
2180 def testSendmsgExcessCmsgReject(self):
2181 # Check that sendmsg() rejects excess ancillary data items
2182 # when the number that can be sent is limited.
2183 self.assertEqual(self.serv_sock.recv(1000), b"done")
2184
2185 def _testSendmsgExcessCmsgReject(self):
2186 if not hasattr(socket, "CMSG_SPACE"):
2187 # Can only send one item
Andrew Svetlov0832af62012-12-18 23:10:48 +02002188 with self.assertRaises(OSError) as cm:
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002189 self.sendmsgToServer([MSG], [(0, 0, b""), (0, 0, b"")])
2190 self.assertIsNone(cm.exception.errno)
2191 self.sendToServer(b"done")
2192
2193 def testSendmsgAfterClose(self):
2194 # Check that sendmsg() fails on a closed socket.
2195 pass
2196
2197 def _testSendmsgAfterClose(self):
2198 self.cli_sock.close()
Andrew Svetlov0832af62012-12-18 23:10:48 +02002199 self.assertRaises(OSError, self.sendmsgToServer, [MSG])
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002200
2201
2202class SendmsgStreamTests(SendmsgTests):
2203 # Tests for sendmsg() which require a stream socket and do not
2204 # involve recvmsg() or recvmsg_into().
2205
2206 def testSendmsgExplicitNoneAddr(self):
2207 # Check that peer address can be specified as None.
2208 self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
2209
2210 def _testSendmsgExplicitNoneAddr(self):
2211 self.assertEqual(self.sendmsgToServer([MSG], [], 0, None), len(MSG))
2212
2213 def testSendmsgTimeout(self):
2214 # Check that timeout works with sendmsg().
2215 self.assertEqual(self.serv_sock.recv(512), b"a"*512)
2216 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
2217
2218 def _testSendmsgTimeout(self):
2219 try:
2220 self.cli_sock.settimeout(0.03)
2221 with self.assertRaises(socket.timeout):
2222 while True:
2223 self.sendmsgToServer([b"a"*512])
2224 finally:
2225 self.misc_event.set()
2226
2227 # XXX: would be nice to have more tests for sendmsg flags argument.
2228
2229 # Linux supports MSG_DONTWAIT when sending, but in general, it
2230 # only works when receiving. Could add other platforms if they
2231 # support it too.
Serhiy Storchakaabde2c12014-11-19 13:21:13 +02002232 @skipWithClientIf(sys.platform not in {"linux"},
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002233 "MSG_DONTWAIT not known to work on this platform when "
2234 "sending")
2235 def testSendmsgDontWait(self):
2236 # Check that MSG_DONTWAIT in flags causes non-blocking behaviour.
2237 self.assertEqual(self.serv_sock.recv(512), b"a"*512)
2238 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
2239
2240 @testSendmsgDontWait.client_skip
2241 def _testSendmsgDontWait(self):
2242 try:
Andrew Svetlov0832af62012-12-18 23:10:48 +02002243 with self.assertRaises(OSError) as cm:
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002244 while True:
2245 self.sendmsgToServer([b"a"*512], [], socket.MSG_DONTWAIT)
2246 self.assertIn(cm.exception.errno,
2247 (errno.EAGAIN, errno.EWOULDBLOCK))
2248 finally:
2249 self.misc_event.set()
2250
2251
2252class SendmsgConnectionlessTests(SendmsgTests):
2253 # Tests for sendmsg() which require a connectionless-mode
2254 # (e.g. datagram) socket, and do not involve recvmsg() or
2255 # recvmsg_into().
2256
2257 def testSendmsgNoDestAddr(self):
2258 # Check that sendmsg() fails when no destination address is
2259 # given for unconnected socket.
2260 pass
2261
2262 def _testSendmsgNoDestAddr(self):
Andrew Svetlov0832af62012-12-18 23:10:48 +02002263 self.assertRaises(OSError, self.cli_sock.sendmsg,
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002264 [MSG])
Andrew Svetlov0832af62012-12-18 23:10:48 +02002265 self.assertRaises(OSError, self.cli_sock.sendmsg,
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002266 [MSG], [], 0, None)
2267
2268
2269class RecvmsgGenericTests(SendrecvmsgBase):
2270 # Tests for recvmsg() which can also be emulated using
2271 # recvmsg_into(), and can use any socket type.
2272
2273 def testRecvmsg(self):
2274 # Receive a simple message with recvmsg[_into]().
2275 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, len(MSG))
2276 self.assertEqual(msg, MSG)
2277 self.checkRecvmsgAddress(addr, self.cli_addr)
2278 self.assertEqual(ancdata, [])
2279 self.checkFlags(flags, eor=True)
2280
2281 def _testRecvmsg(self):
2282 self.sendToServer(MSG)
2283
2284 def testRecvmsgExplicitDefaults(self):
2285 # Test recvmsg[_into]() with default arguments provided explicitly.
2286 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
2287 len(MSG), 0, 0)
2288 self.assertEqual(msg, MSG)
2289 self.checkRecvmsgAddress(addr, self.cli_addr)
2290 self.assertEqual(ancdata, [])
2291 self.checkFlags(flags, eor=True)
2292
2293 def _testRecvmsgExplicitDefaults(self):
2294 self.sendToServer(MSG)
2295
2296 def testRecvmsgShorter(self):
2297 # Receive a message smaller than buffer.
2298 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
2299 len(MSG) + 42)
2300 self.assertEqual(msg, MSG)
2301 self.checkRecvmsgAddress(addr, self.cli_addr)
2302 self.assertEqual(ancdata, [])
2303 self.checkFlags(flags, eor=True)
2304
2305 def _testRecvmsgShorter(self):
2306 self.sendToServer(MSG)
2307
Charles-François Natali8619cd72011-10-03 19:43:15 +02002308 # FreeBSD < 8 doesn't always set the MSG_TRUNC flag when a truncated
2309 # datagram is received (issue #13001).
2310 @support.requires_freebsd_version(8)
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002311 def testRecvmsgTrunc(self):
2312 # Receive part of message, check for truncation indicators.
2313 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
2314 len(MSG) - 3)
2315 self.assertEqual(msg, MSG[:-3])
2316 self.checkRecvmsgAddress(addr, self.cli_addr)
2317 self.assertEqual(ancdata, [])
2318 self.checkFlags(flags, eor=False)
2319
Charles-François Natali8619cd72011-10-03 19:43:15 +02002320 @support.requires_freebsd_version(8)
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002321 def _testRecvmsgTrunc(self):
2322 self.sendToServer(MSG)
2323
2324 def testRecvmsgShortAncillaryBuf(self):
2325 # Test ancillary data buffer too small to hold any ancillary data.
2326 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
2327 len(MSG), 1)
2328 self.assertEqual(msg, MSG)
2329 self.checkRecvmsgAddress(addr, self.cli_addr)
2330 self.assertEqual(ancdata, [])
2331 self.checkFlags(flags, eor=True)
2332
2333 def _testRecvmsgShortAncillaryBuf(self):
2334 self.sendToServer(MSG)
2335
2336 def testRecvmsgLongAncillaryBuf(self):
2337 # Test large ancillary data buffer.
2338 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
2339 len(MSG), 10240)
2340 self.assertEqual(msg, MSG)
2341 self.checkRecvmsgAddress(addr, self.cli_addr)
2342 self.assertEqual(ancdata, [])
2343 self.checkFlags(flags, eor=True)
2344
2345 def _testRecvmsgLongAncillaryBuf(self):
2346 self.sendToServer(MSG)
2347
2348 def testRecvmsgAfterClose(self):
2349 # Check that recvmsg[_into]() fails on a closed socket.
2350 self.serv_sock.close()
Andrew Svetlov0832af62012-12-18 23:10:48 +02002351 self.assertRaises(OSError, self.doRecvmsg, self.serv_sock, 1024)
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002352
2353 def _testRecvmsgAfterClose(self):
2354 pass
2355
2356 def testRecvmsgTimeout(self):
2357 # Check that timeout works.
2358 try:
2359 self.serv_sock.settimeout(0.03)
2360 self.assertRaises(socket.timeout,
2361 self.doRecvmsg, self.serv_sock, len(MSG))
2362 finally:
2363 self.misc_event.set()
2364
2365 def _testRecvmsgTimeout(self):
2366 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
2367
2368 @requireAttrs(socket, "MSG_PEEK")
2369 def testRecvmsgPeek(self):
2370 # Check that MSG_PEEK in flags enables examination of pending
2371 # data without consuming it.
2372
2373 # Receive part of data with MSG_PEEK.
2374 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
2375 len(MSG) - 3, 0,
2376 socket.MSG_PEEK)
2377 self.assertEqual(msg, MSG[:-3])
2378 self.checkRecvmsgAddress(addr, self.cli_addr)
2379 self.assertEqual(ancdata, [])
2380 # Ignoring MSG_TRUNC here (so this test is the same for stream
2381 # and datagram sockets). Some wording in POSIX seems to
2382 # suggest that it needn't be set when peeking, but that may
2383 # just be a slip.
2384 self.checkFlags(flags, eor=False,
2385 ignore=getattr(socket, "MSG_TRUNC", 0))
2386
2387 # Receive all data with MSG_PEEK.
2388 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
2389 len(MSG), 0,
2390 socket.MSG_PEEK)
2391 self.assertEqual(msg, MSG)
2392 self.checkRecvmsgAddress(addr, self.cli_addr)
2393 self.assertEqual(ancdata, [])
2394 self.checkFlags(flags, eor=True)
2395
2396 # Check that the same data can still be received normally.
2397 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, len(MSG))
2398 self.assertEqual(msg, MSG)
2399 self.checkRecvmsgAddress(addr, self.cli_addr)
2400 self.assertEqual(ancdata, [])
2401 self.checkFlags(flags, eor=True)
2402
2403 @testRecvmsgPeek.client_skip
2404 def _testRecvmsgPeek(self):
2405 self.sendToServer(MSG)
2406
2407 @requireAttrs(socket.socket, "sendmsg")
2408 def testRecvmsgFromSendmsg(self):
2409 # Test receiving with recvmsg[_into]() when message is sent
2410 # using sendmsg().
2411 self.serv_sock.settimeout(self.fail_timeout)
2412 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, len(MSG))
2413 self.assertEqual(msg, MSG)
2414 self.checkRecvmsgAddress(addr, self.cli_addr)
2415 self.assertEqual(ancdata, [])
2416 self.checkFlags(flags, eor=True)
2417
2418 @testRecvmsgFromSendmsg.client_skip
2419 def _testRecvmsgFromSendmsg(self):
2420 self.assertEqual(self.sendmsgToServer([MSG[:3], MSG[3:]]), len(MSG))
2421
2422
2423class RecvmsgGenericStreamTests(RecvmsgGenericTests):
2424 # Tests which require a stream socket and can use either recvmsg()
2425 # or recvmsg_into().
2426
2427 def testRecvmsgEOF(self):
2428 # Receive end-of-stream indicator (b"", peer socket closed).
2429 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, 1024)
2430 self.assertEqual(msg, b"")
2431 self.checkRecvmsgAddress(addr, self.cli_addr)
2432 self.assertEqual(ancdata, [])
2433 self.checkFlags(flags, eor=None) # Might not have end-of-record marker
2434
2435 def _testRecvmsgEOF(self):
2436 self.cli_sock.close()
2437
2438 def testRecvmsgOverflow(self):
2439 # Receive a message in more than one chunk.
2440 seg1, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
2441 len(MSG) - 3)
2442 self.checkRecvmsgAddress(addr, self.cli_addr)
2443 self.assertEqual(ancdata, [])
2444 self.checkFlags(flags, eor=False)
2445
2446 seg2, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, 1024)
2447 self.checkRecvmsgAddress(addr, self.cli_addr)
2448 self.assertEqual(ancdata, [])
2449 self.checkFlags(flags, eor=True)
2450
2451 msg = seg1 + seg2
2452 self.assertEqual(msg, MSG)
2453
2454 def _testRecvmsgOverflow(self):
2455 self.sendToServer(MSG)
2456
2457
2458class RecvmsgTests(RecvmsgGenericTests):
2459 # Tests for recvmsg() which can use any socket type.
2460
2461 def testRecvmsgBadArgs(self):
2462 # Check that recvmsg() rejects invalid arguments.
2463 self.assertRaises(TypeError, self.serv_sock.recvmsg)
2464 self.assertRaises(ValueError, self.serv_sock.recvmsg,
2465 -1, 0, 0)
2466 self.assertRaises(ValueError, self.serv_sock.recvmsg,
2467 len(MSG), -1, 0)
2468 self.assertRaises(TypeError, self.serv_sock.recvmsg,
2469 [bytearray(10)], 0, 0)
2470 self.assertRaises(TypeError, self.serv_sock.recvmsg,
2471 object(), 0, 0)
2472 self.assertRaises(TypeError, self.serv_sock.recvmsg,
2473 len(MSG), object(), 0)
2474 self.assertRaises(TypeError, self.serv_sock.recvmsg,
2475 len(MSG), 0, object())
2476
2477 msg, ancdata, flags, addr = self.serv_sock.recvmsg(len(MSG), 0, 0)
2478 self.assertEqual(msg, MSG)
2479 self.checkRecvmsgAddress(addr, self.cli_addr)
2480 self.assertEqual(ancdata, [])
2481 self.checkFlags(flags, eor=True)
2482
2483 def _testRecvmsgBadArgs(self):
2484 self.sendToServer(MSG)
2485
2486
2487class RecvmsgIntoTests(RecvmsgIntoMixin, RecvmsgGenericTests):
2488 # Tests for recvmsg_into() which can use any socket type.
2489
2490 def testRecvmsgIntoBadArgs(self):
2491 # Check that recvmsg_into() rejects invalid arguments.
2492 buf = bytearray(len(MSG))
2493 self.assertRaises(TypeError, self.serv_sock.recvmsg_into)
2494 self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
2495 len(MSG), 0, 0)
2496 self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
2497 buf, 0, 0)
2498 self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
2499 [object()], 0, 0)
2500 self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
2501 [b"I'm not writable"], 0, 0)
2502 self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
2503 [buf, object()], 0, 0)
2504 self.assertRaises(ValueError, self.serv_sock.recvmsg_into,
2505 [buf], -1, 0)
2506 self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
2507 [buf], object(), 0)
2508 self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
2509 [buf], 0, object())
2510
2511 nbytes, ancdata, flags, addr = self.serv_sock.recvmsg_into([buf], 0, 0)
2512 self.assertEqual(nbytes, len(MSG))
2513 self.assertEqual(buf, bytearray(MSG))
2514 self.checkRecvmsgAddress(addr, self.cli_addr)
2515 self.assertEqual(ancdata, [])
2516 self.checkFlags(flags, eor=True)
2517
2518 def _testRecvmsgIntoBadArgs(self):
2519 self.sendToServer(MSG)
2520
2521 def testRecvmsgIntoGenerator(self):
2522 # Receive into buffer obtained from a generator (not a sequence).
2523 buf = bytearray(len(MSG))
2524 nbytes, ancdata, flags, addr = self.serv_sock.recvmsg_into(
2525 (o for o in [buf]))
2526 self.assertEqual(nbytes, len(MSG))
2527 self.assertEqual(buf, bytearray(MSG))
2528 self.checkRecvmsgAddress(addr, self.cli_addr)
2529 self.assertEqual(ancdata, [])
2530 self.checkFlags(flags, eor=True)
2531
2532 def _testRecvmsgIntoGenerator(self):
2533 self.sendToServer(MSG)
2534
2535 def testRecvmsgIntoArray(self):
2536 # Receive into an array rather than the usual bytearray.
2537 buf = array.array("B", [0] * len(MSG))
2538 nbytes, ancdata, flags, addr = self.serv_sock.recvmsg_into([buf])
2539 self.assertEqual(nbytes, len(MSG))
Nadeem Vawda3d1706f2011-08-22 09:46:56 +02002540 self.assertEqual(buf.tobytes(), MSG)
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002541 self.checkRecvmsgAddress(addr, self.cli_addr)
2542 self.assertEqual(ancdata, [])
2543 self.checkFlags(flags, eor=True)
2544
2545 def _testRecvmsgIntoArray(self):
2546 self.sendToServer(MSG)
2547
2548 def testRecvmsgIntoScatter(self):
2549 # Receive into multiple buffers (scatter write).
2550 b1 = bytearray(b"----")
2551 b2 = bytearray(b"0123456789")
2552 b3 = bytearray(b"--------------")
2553 nbytes, ancdata, flags, addr = self.serv_sock.recvmsg_into(
2554 [b1, memoryview(b2)[2:9], b3])
2555 self.assertEqual(nbytes, len(b"Mary had a little lamb"))
2556 self.assertEqual(b1, bytearray(b"Mary"))
2557 self.assertEqual(b2, bytearray(b"01 had a 9"))
2558 self.assertEqual(b3, bytearray(b"little lamb---"))
2559 self.checkRecvmsgAddress(addr, self.cli_addr)
2560 self.assertEqual(ancdata, [])
2561 self.checkFlags(flags, eor=True)
2562
2563 def _testRecvmsgIntoScatter(self):
2564 self.sendToServer(b"Mary had a little lamb")
2565
2566
2567class CmsgMacroTests(unittest.TestCase):
2568 # Test the functions CMSG_LEN() and CMSG_SPACE(). Tests
2569 # assumptions used by sendmsg() and recvmsg[_into](), which share
2570 # code with these functions.
2571
2572 # Match the definition in socketmodule.c
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02002573 try:
2574 import _testcapi
2575 except ImportError:
2576 socklen_t_limit = 0x7fffffff
2577 else:
2578 socklen_t_limit = min(0x7fffffff, _testcapi.INT_MAX)
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002579
2580 @requireAttrs(socket, "CMSG_LEN")
2581 def testCMSG_LEN(self):
2582 # Test CMSG_LEN() with various valid and invalid values,
2583 # checking the assumptions used by recvmsg() and sendmsg().
2584 toobig = self.socklen_t_limit - socket.CMSG_LEN(0) + 1
2585 values = list(range(257)) + list(range(toobig - 257, toobig))
2586
2587 # struct cmsghdr has at least three members, two of which are ints
2588 self.assertGreater(socket.CMSG_LEN(0), array.array("i").itemsize * 2)
2589 for n in values:
2590 ret = socket.CMSG_LEN(n)
2591 # This is how recvmsg() calculates the data size
2592 self.assertEqual(ret - socket.CMSG_LEN(0), n)
2593 self.assertLessEqual(ret, self.socklen_t_limit)
2594
2595 self.assertRaises(OverflowError, socket.CMSG_LEN, -1)
2596 # sendmsg() shares code with these functions, and requires
2597 # that it reject values over the limit.
2598 self.assertRaises(OverflowError, socket.CMSG_LEN, toobig)
2599 self.assertRaises(OverflowError, socket.CMSG_LEN, sys.maxsize)
2600
2601 @requireAttrs(socket, "CMSG_SPACE")
2602 def testCMSG_SPACE(self):
2603 # Test CMSG_SPACE() with various valid and invalid values,
2604 # checking the assumptions used by sendmsg().
2605 toobig = self.socklen_t_limit - socket.CMSG_SPACE(1) + 1
2606 values = list(range(257)) + list(range(toobig - 257, toobig))
2607
2608 last = socket.CMSG_SPACE(0)
2609 # struct cmsghdr has at least three members, two of which are ints
2610 self.assertGreater(last, array.array("i").itemsize * 2)
2611 for n in values:
2612 ret = socket.CMSG_SPACE(n)
2613 self.assertGreaterEqual(ret, last)
2614 self.assertGreaterEqual(ret, socket.CMSG_LEN(n))
2615 self.assertGreaterEqual(ret, n + socket.CMSG_LEN(0))
2616 self.assertLessEqual(ret, self.socklen_t_limit)
2617 last = ret
2618
2619 self.assertRaises(OverflowError, socket.CMSG_SPACE, -1)
2620 # sendmsg() shares code with these functions, and requires
2621 # that it reject values over the limit.
2622 self.assertRaises(OverflowError, socket.CMSG_SPACE, toobig)
2623 self.assertRaises(OverflowError, socket.CMSG_SPACE, sys.maxsize)
2624
2625
2626class SCMRightsTest(SendrecvmsgServerTimeoutBase):
2627 # Tests for file descriptor passing on Unix-domain sockets.
2628
2629 # Invalid file descriptor value that's unlikely to evaluate to a
2630 # real FD even if one of its bytes is replaced with a different
2631 # value (which shouldn't actually happen).
2632 badfd = -0x5555
2633
2634 def newFDs(self, n):
2635 # Return a list of n file descriptors for newly-created files
2636 # containing their list indices as ASCII numbers.
2637 fds = []
2638 for i in range(n):
2639 fd, path = tempfile.mkstemp()
2640 self.addCleanup(os.unlink, path)
2641 self.addCleanup(os.close, fd)
2642 os.write(fd, str(i).encode())
2643 fds.append(fd)
2644 return fds
2645
2646 def checkFDs(self, fds):
2647 # Check that the file descriptors in the given list contain
2648 # their correct list indices as ASCII numbers.
2649 for n, fd in enumerate(fds):
2650 os.lseek(fd, 0, os.SEEK_SET)
2651 self.assertEqual(os.read(fd, 1024), str(n).encode())
2652
2653 def registerRecvmsgResult(self, result):
2654 self.addCleanup(self.closeRecvmsgFDs, result)
2655
2656 def closeRecvmsgFDs(self, recvmsg_result):
2657 # Close all file descriptors specified in the ancillary data
2658 # of the given return value from recvmsg() or recvmsg_into().
2659 for cmsg_level, cmsg_type, cmsg_data in recvmsg_result[1]:
2660 if (cmsg_level == socket.SOL_SOCKET and
2661 cmsg_type == socket.SCM_RIGHTS):
2662 fds = array.array("i")
Nadeem Vawda3d1706f2011-08-22 09:46:56 +02002663 fds.frombytes(cmsg_data[:
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002664 len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
2665 for fd in fds:
2666 os.close(fd)
2667
2668 def createAndSendFDs(self, n):
2669 # Send n new file descriptors created by newFDs() to the
2670 # server, with the constant MSG as the non-ancillary data.
2671 self.assertEqual(
2672 self.sendmsgToServer([MSG],
2673 [(socket.SOL_SOCKET,
2674 socket.SCM_RIGHTS,
2675 array.array("i", self.newFDs(n)))]),
2676 len(MSG))
2677
2678 def checkRecvmsgFDs(self, numfds, result, maxcmsgs=1, ignoreflags=0):
2679 # Check that constant MSG was received with numfds file
2680 # descriptors in a maximum of maxcmsgs control messages (which
2681 # must contain only complete integers). By default, check
2682 # that MSG_CTRUNC is unset, but ignore any flags in
2683 # ignoreflags.
2684 msg, ancdata, flags, addr = result
2685 self.assertEqual(msg, MSG)
2686 self.checkRecvmsgAddress(addr, self.cli_addr)
2687 self.checkFlags(flags, eor=True, checkunset=socket.MSG_CTRUNC,
2688 ignore=ignoreflags)
2689
2690 self.assertIsInstance(ancdata, list)
2691 self.assertLessEqual(len(ancdata), maxcmsgs)
2692 fds = array.array("i")
2693 for item in ancdata:
2694 self.assertIsInstance(item, tuple)
2695 cmsg_level, cmsg_type, cmsg_data = item
2696 self.assertEqual(cmsg_level, socket.SOL_SOCKET)
2697 self.assertEqual(cmsg_type, socket.SCM_RIGHTS)
2698 self.assertIsInstance(cmsg_data, bytes)
2699 self.assertEqual(len(cmsg_data) % SIZEOF_INT, 0)
Nadeem Vawda3d1706f2011-08-22 09:46:56 +02002700 fds.frombytes(cmsg_data)
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002701
2702 self.assertEqual(len(fds), numfds)
2703 self.checkFDs(fds)
2704
2705 def testFDPassSimple(self):
2706 # Pass a single FD (array read from bytes object).
2707 self.checkRecvmsgFDs(1, self.doRecvmsg(self.serv_sock,
2708 len(MSG), 10240))
2709
2710 def _testFDPassSimple(self):
2711 self.assertEqual(
2712 self.sendmsgToServer(
2713 [MSG],
2714 [(socket.SOL_SOCKET,
2715 socket.SCM_RIGHTS,
Nadeem Vawda3d1706f2011-08-22 09:46:56 +02002716 array.array("i", self.newFDs(1)).tobytes())]),
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002717 len(MSG))
2718
2719 def testMultipleFDPass(self):
2720 # Pass multiple FDs in a single array.
2721 self.checkRecvmsgFDs(4, self.doRecvmsg(self.serv_sock,
2722 len(MSG), 10240))
2723
2724 def _testMultipleFDPass(self):
2725 self.createAndSendFDs(4)
2726
2727 @requireAttrs(socket, "CMSG_SPACE")
2728 def testFDPassCMSG_SPACE(self):
2729 # Test using CMSG_SPACE() to calculate ancillary buffer size.
2730 self.checkRecvmsgFDs(
2731 4, self.doRecvmsg(self.serv_sock, len(MSG),
2732 socket.CMSG_SPACE(4 * SIZEOF_INT)))
2733
2734 @testFDPassCMSG_SPACE.client_skip
2735 def _testFDPassCMSG_SPACE(self):
2736 self.createAndSendFDs(4)
2737
2738 def testFDPassCMSG_LEN(self):
2739 # Test using CMSG_LEN() to calculate ancillary buffer size.
2740 self.checkRecvmsgFDs(1,
2741 self.doRecvmsg(self.serv_sock, len(MSG),
2742 socket.CMSG_LEN(4 * SIZEOF_INT)),
2743 # RFC 3542 says implementations may set
2744 # MSG_CTRUNC if there isn't enough space
2745 # for trailing padding.
2746 ignoreflags=socket.MSG_CTRUNC)
2747
2748 def _testFDPassCMSG_LEN(self):
2749 self.createAndSendFDs(1)
2750
Charles-Francois Natalid66b10e2013-05-20 19:08:19 +02002751 @unittest.skipIf(sys.platform == "darwin", "skipping, see issue #12958")
Robert Collins43cbbe22015-08-03 10:36:04 +12002752 @unittest.skipIf(sys.platform.startswith("aix"), "skipping, see issue #22397")
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002753 @requireAttrs(socket, "CMSG_SPACE")
2754 def testFDPassSeparate(self):
2755 # Pass two FDs in two separate arrays. Arrays may be combined
2756 # into a single control message by the OS.
2757 self.checkRecvmsgFDs(2,
2758 self.doRecvmsg(self.serv_sock, len(MSG), 10240),
2759 maxcmsgs=2)
2760
2761 @testFDPassSeparate.client_skip
Charles-Francois Natalid66b10e2013-05-20 19:08:19 +02002762 @unittest.skipIf(sys.platform == "darwin", "skipping, see issue #12958")
Robert Collins43cbbe22015-08-03 10:36:04 +12002763 @unittest.skipIf(sys.platform.startswith("aix"), "skipping, see issue #22397")
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002764 def _testFDPassSeparate(self):
2765 fd0, fd1 = self.newFDs(2)
2766 self.assertEqual(
2767 self.sendmsgToServer([MSG], [(socket.SOL_SOCKET,
2768 socket.SCM_RIGHTS,
2769 array.array("i", [fd0])),
2770 (socket.SOL_SOCKET,
2771 socket.SCM_RIGHTS,
2772 array.array("i", [fd1]))]),
2773 len(MSG))
2774
Charles-Francois Natalid66b10e2013-05-20 19:08:19 +02002775 @unittest.skipIf(sys.platform == "darwin", "skipping, see issue #12958")
Robert Collins43cbbe22015-08-03 10:36:04 +12002776 @unittest.skipIf(sys.platform.startswith("aix"), "skipping, see issue #22397")
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002777 @requireAttrs(socket, "CMSG_SPACE")
2778 def testFDPassSeparateMinSpace(self):
2779 # Pass two FDs in two separate arrays, receiving them into the
2780 # minimum space for two arrays.
2781 self.checkRecvmsgFDs(2,
2782 self.doRecvmsg(self.serv_sock, len(MSG),
2783 socket.CMSG_SPACE(SIZEOF_INT) +
2784 socket.CMSG_LEN(SIZEOF_INT)),
2785 maxcmsgs=2, ignoreflags=socket.MSG_CTRUNC)
2786
2787 @testFDPassSeparateMinSpace.client_skip
Charles-Francois Natalid66b10e2013-05-20 19:08:19 +02002788 @unittest.skipIf(sys.platform == "darwin", "skipping, see issue #12958")
Robert Collins43cbbe22015-08-03 10:36:04 +12002789 @unittest.skipIf(sys.platform.startswith("aix"), "skipping, see issue #22397")
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002790 def _testFDPassSeparateMinSpace(self):
2791 fd0, fd1 = self.newFDs(2)
2792 self.assertEqual(
2793 self.sendmsgToServer([MSG], [(socket.SOL_SOCKET,
2794 socket.SCM_RIGHTS,
2795 array.array("i", [fd0])),
2796 (socket.SOL_SOCKET,
2797 socket.SCM_RIGHTS,
2798 array.array("i", [fd1]))]),
2799 len(MSG))
2800
2801 def sendAncillaryIfPossible(self, msg, ancdata):
2802 # Try to send msg and ancdata to server, but if the system
2803 # call fails, just send msg with no ancillary data.
2804 try:
2805 nbytes = self.sendmsgToServer([msg], ancdata)
Andrew Svetlov0832af62012-12-18 23:10:48 +02002806 except OSError as e:
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002807 # Check that it was the system call that failed
2808 self.assertIsInstance(e.errno, int)
2809 nbytes = self.sendmsgToServer([msg])
2810 self.assertEqual(nbytes, len(msg))
2811
Brett Cannon3bbad122015-12-28 17:21:44 -08002812 @unittest.skipIf(sys.platform == "darwin", "see issue #24725")
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002813 def testFDPassEmpty(self):
2814 # Try to pass an empty FD array. Can receive either no array
2815 # or an empty array.
2816 self.checkRecvmsgFDs(0, self.doRecvmsg(self.serv_sock,
2817 len(MSG), 10240),
2818 ignoreflags=socket.MSG_CTRUNC)
2819
2820 def _testFDPassEmpty(self):
2821 self.sendAncillaryIfPossible(MSG, [(socket.SOL_SOCKET,
2822 socket.SCM_RIGHTS,
2823 b"")])
2824
2825 def testFDPassPartialInt(self):
2826 # Try to pass a truncated FD array.
2827 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
2828 len(MSG), 10240)
2829 self.assertEqual(msg, MSG)
2830 self.checkRecvmsgAddress(addr, self.cli_addr)
2831 self.checkFlags(flags, eor=True, ignore=socket.MSG_CTRUNC)
2832 self.assertLessEqual(len(ancdata), 1)
2833 for cmsg_level, cmsg_type, cmsg_data in ancdata:
2834 self.assertEqual(cmsg_level, socket.SOL_SOCKET)
2835 self.assertEqual(cmsg_type, socket.SCM_RIGHTS)
2836 self.assertLess(len(cmsg_data), SIZEOF_INT)
2837
2838 def _testFDPassPartialInt(self):
2839 self.sendAncillaryIfPossible(
2840 MSG,
2841 [(socket.SOL_SOCKET,
2842 socket.SCM_RIGHTS,
Nadeem Vawda3d1706f2011-08-22 09:46:56 +02002843 array.array("i", [self.badfd]).tobytes()[:-1])])
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002844
2845 @requireAttrs(socket, "CMSG_SPACE")
2846 def testFDPassPartialIntInMiddle(self):
2847 # Try to pass two FD arrays, the first of which is truncated.
2848 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
2849 len(MSG), 10240)
2850 self.assertEqual(msg, MSG)
2851 self.checkRecvmsgAddress(addr, self.cli_addr)
2852 self.checkFlags(flags, eor=True, ignore=socket.MSG_CTRUNC)
2853 self.assertLessEqual(len(ancdata), 2)
2854 fds = array.array("i")
2855 # Arrays may have been combined in a single control message
2856 for cmsg_level, cmsg_type, cmsg_data in ancdata:
2857 self.assertEqual(cmsg_level, socket.SOL_SOCKET)
2858 self.assertEqual(cmsg_type, socket.SCM_RIGHTS)
Nadeem Vawda3d1706f2011-08-22 09:46:56 +02002859 fds.frombytes(cmsg_data[:
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002860 len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
2861 self.assertLessEqual(len(fds), 2)
2862 self.checkFDs(fds)
2863
2864 @testFDPassPartialIntInMiddle.client_skip
2865 def _testFDPassPartialIntInMiddle(self):
2866 fd0, fd1 = self.newFDs(2)
2867 self.sendAncillaryIfPossible(
2868 MSG,
2869 [(socket.SOL_SOCKET,
2870 socket.SCM_RIGHTS,
Nadeem Vawda3d1706f2011-08-22 09:46:56 +02002871 array.array("i", [fd0, self.badfd]).tobytes()[:-1]),
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002872 (socket.SOL_SOCKET,
2873 socket.SCM_RIGHTS,
2874 array.array("i", [fd1]))])
2875
2876 def checkTruncatedHeader(self, result, ignoreflags=0):
2877 # Check that no ancillary data items are returned when data is
2878 # truncated inside the cmsghdr structure.
2879 msg, ancdata, flags, addr = result
2880 self.assertEqual(msg, MSG)
2881 self.checkRecvmsgAddress(addr, self.cli_addr)
2882 self.assertEqual(ancdata, [])
2883 self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC,
2884 ignore=ignoreflags)
2885
2886 def testCmsgTruncNoBufSize(self):
2887 # Check that no ancillary data is received when no buffer size
2888 # is specified.
2889 self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG)),
2890 # BSD seems to set MSG_CTRUNC only
2891 # if an item has been partially
2892 # received.
2893 ignoreflags=socket.MSG_CTRUNC)
2894
2895 def _testCmsgTruncNoBufSize(self):
2896 self.createAndSendFDs(1)
2897
2898 def testCmsgTrunc0(self):
2899 # Check that no ancillary data is received when buffer size is 0.
2900 self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG), 0),
2901 ignoreflags=socket.MSG_CTRUNC)
2902
2903 def _testCmsgTrunc0(self):
2904 self.createAndSendFDs(1)
2905
2906 # Check that no ancillary data is returned for various non-zero
2907 # (but still too small) buffer sizes.
2908
2909 def testCmsgTrunc1(self):
2910 self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG), 1))
2911
2912 def _testCmsgTrunc1(self):
2913 self.createAndSendFDs(1)
2914
2915 def testCmsgTrunc2Int(self):
2916 # The cmsghdr structure has at least three members, two of
2917 # which are ints, so we still shouldn't see any ancillary
2918 # data.
2919 self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG),
2920 SIZEOF_INT * 2))
2921
2922 def _testCmsgTrunc2Int(self):
2923 self.createAndSendFDs(1)
2924
2925 def testCmsgTruncLen0Minus1(self):
2926 self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG),
2927 socket.CMSG_LEN(0) - 1))
2928
2929 def _testCmsgTruncLen0Minus1(self):
2930 self.createAndSendFDs(1)
2931
2932 # The following tests try to truncate the control message in the
2933 # middle of the FD array.
2934
2935 def checkTruncatedArray(self, ancbuf, maxdata, mindata=0):
2936 # Check that file descriptor data is truncated to between
2937 # mindata and maxdata bytes when received with buffer size
2938 # ancbuf, and that any complete file descriptor numbers are
2939 # valid.
2940 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
2941 len(MSG), ancbuf)
2942 self.assertEqual(msg, MSG)
2943 self.checkRecvmsgAddress(addr, self.cli_addr)
2944 self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC)
2945
2946 if mindata == 0 and ancdata == []:
2947 return
2948 self.assertEqual(len(ancdata), 1)
2949 cmsg_level, cmsg_type, cmsg_data = ancdata[0]
2950 self.assertEqual(cmsg_level, socket.SOL_SOCKET)
2951 self.assertEqual(cmsg_type, socket.SCM_RIGHTS)
2952 self.assertGreaterEqual(len(cmsg_data), mindata)
2953 self.assertLessEqual(len(cmsg_data), maxdata)
2954 fds = array.array("i")
Nadeem Vawda3d1706f2011-08-22 09:46:56 +02002955 fds.frombytes(cmsg_data[:
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002956 len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
2957 self.checkFDs(fds)
2958
2959 def testCmsgTruncLen0(self):
2960 self.checkTruncatedArray(ancbuf=socket.CMSG_LEN(0), maxdata=0)
2961
2962 def _testCmsgTruncLen0(self):
2963 self.createAndSendFDs(1)
2964
2965 def testCmsgTruncLen0Plus1(self):
2966 self.checkTruncatedArray(ancbuf=socket.CMSG_LEN(0) + 1, maxdata=1)
2967
2968 def _testCmsgTruncLen0Plus1(self):
2969 self.createAndSendFDs(2)
2970
2971 def testCmsgTruncLen1(self):
2972 self.checkTruncatedArray(ancbuf=socket.CMSG_LEN(SIZEOF_INT),
2973 maxdata=SIZEOF_INT)
2974
2975 def _testCmsgTruncLen1(self):
2976 self.createAndSendFDs(2)
2977
2978 def testCmsgTruncLen2Minus1(self):
2979 self.checkTruncatedArray(ancbuf=socket.CMSG_LEN(2 * SIZEOF_INT) - 1,
2980 maxdata=(2 * SIZEOF_INT) - 1)
2981
2982 def _testCmsgTruncLen2Minus1(self):
2983 self.createAndSendFDs(2)
2984
2985
2986class RFC3542AncillaryTest(SendrecvmsgServerTimeoutBase):
2987 # Test sendmsg() and recvmsg[_into]() using the ancillary data
2988 # features of the RFC 3542 Advanced Sockets API for IPv6.
2989 # Currently we can only handle certain data items (e.g. traffic
2990 # class, hop limit, MTU discovery and fragmentation settings)
2991 # without resorting to unportable means such as the struct module,
2992 # but the tests here are aimed at testing the ancillary data
2993 # handling in sendmsg() and recvmsg() rather than the IPv6 API
2994 # itself.
2995
2996 # Test value to use when setting hop limit of packet
2997 hop_limit = 2
2998
2999 # Test value to use when setting traffic class of packet.
3000 # -1 means "use kernel default".
3001 traffic_class = -1
3002
3003 def ancillaryMapping(self, ancdata):
3004 # Given ancillary data list ancdata, return a mapping from
3005 # pairs (cmsg_level, cmsg_type) to corresponding cmsg_data.
3006 # Check that no (level, type) pair appears more than once.
3007 d = {}
3008 for cmsg_level, cmsg_type, cmsg_data in ancdata:
3009 self.assertNotIn((cmsg_level, cmsg_type), d)
3010 d[(cmsg_level, cmsg_type)] = cmsg_data
3011 return d
3012
3013 def checkHopLimit(self, ancbufsize, maxhop=255, ignoreflags=0):
3014 # Receive hop limit into ancbufsize bytes of ancillary data
3015 # space. Check that data is MSG, ancillary data is not
3016 # truncated (but ignore any flags in ignoreflags), and hop
3017 # limit is between 0 and maxhop inclusive.
3018 self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
3019 socket.IPV6_RECVHOPLIMIT, 1)
3020 self.misc_event.set()
3021 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
3022 len(MSG), ancbufsize)
3023
3024 self.assertEqual(msg, MSG)
3025 self.checkRecvmsgAddress(addr, self.cli_addr)
3026 self.checkFlags(flags, eor=True, checkunset=socket.MSG_CTRUNC,
3027 ignore=ignoreflags)
3028
3029 self.assertEqual(len(ancdata), 1)
3030 self.assertIsInstance(ancdata[0], tuple)
3031 cmsg_level, cmsg_type, cmsg_data = ancdata[0]
3032 self.assertEqual(cmsg_level, socket.IPPROTO_IPV6)
3033 self.assertEqual(cmsg_type, socket.IPV6_HOPLIMIT)
3034 self.assertIsInstance(cmsg_data, bytes)
3035 self.assertEqual(len(cmsg_data), SIZEOF_INT)
3036 a = array.array("i")
Nadeem Vawda3d1706f2011-08-22 09:46:56 +02003037 a.frombytes(cmsg_data)
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003038 self.assertGreaterEqual(a[0], 0)
3039 self.assertLessEqual(a[0], maxhop)
3040
3041 @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
3042 def testRecvHopLimit(self):
3043 # Test receiving the packet hop limit as ancillary data.
3044 self.checkHopLimit(ancbufsize=10240)
3045
3046 @testRecvHopLimit.client_skip
3047 def _testRecvHopLimit(self):
3048 # Need to wait until server has asked to receive ancillary
3049 # data, as implementations are not required to buffer it
3050 # otherwise.
3051 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3052 self.sendToServer(MSG)
3053
3054 @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
3055 def testRecvHopLimitCMSG_SPACE(self):
3056 # Test receiving hop limit, using CMSG_SPACE to calculate buffer size.
3057 self.checkHopLimit(ancbufsize=socket.CMSG_SPACE(SIZEOF_INT))
3058
3059 @testRecvHopLimitCMSG_SPACE.client_skip
3060 def _testRecvHopLimitCMSG_SPACE(self):
3061 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3062 self.sendToServer(MSG)
3063
3064 # Could test receiving into buffer sized using CMSG_LEN, but RFC
3065 # 3542 says portable applications must provide space for trailing
3066 # padding. Implementations may set MSG_CTRUNC if there isn't
3067 # enough space for the padding.
3068
3069 @requireAttrs(socket.socket, "sendmsg")
3070 @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
3071 def testSetHopLimit(self):
3072 # Test setting hop limit on outgoing packet and receiving it
3073 # at the other end.
3074 self.checkHopLimit(ancbufsize=10240, maxhop=self.hop_limit)
3075
3076 @testSetHopLimit.client_skip
3077 def _testSetHopLimit(self):
3078 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3079 self.assertEqual(
3080 self.sendmsgToServer([MSG],
3081 [(socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT,
3082 array.array("i", [self.hop_limit]))]),
3083 len(MSG))
3084
3085 def checkTrafficClassAndHopLimit(self, ancbufsize, maxhop=255,
3086 ignoreflags=0):
3087 # Receive traffic class and hop limit into ancbufsize bytes of
3088 # ancillary data space. Check that data is MSG, ancillary
3089 # data is not truncated (but ignore any flags in ignoreflags),
3090 # and traffic class and hop limit are in range (hop limit no
3091 # more than maxhop).
3092 self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
3093 socket.IPV6_RECVHOPLIMIT, 1)
3094 self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
3095 socket.IPV6_RECVTCLASS, 1)
3096 self.misc_event.set()
3097 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
3098 len(MSG), ancbufsize)
3099
3100 self.assertEqual(msg, MSG)
3101 self.checkRecvmsgAddress(addr, self.cli_addr)
3102 self.checkFlags(flags, eor=True, checkunset=socket.MSG_CTRUNC,
3103 ignore=ignoreflags)
3104 self.assertEqual(len(ancdata), 2)
3105 ancmap = self.ancillaryMapping(ancdata)
3106
3107 tcdata = ancmap[(socket.IPPROTO_IPV6, socket.IPV6_TCLASS)]
3108 self.assertEqual(len(tcdata), SIZEOF_INT)
3109 a = array.array("i")
Nadeem Vawda3d1706f2011-08-22 09:46:56 +02003110 a.frombytes(tcdata)
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003111 self.assertGreaterEqual(a[0], 0)
3112 self.assertLessEqual(a[0], 255)
3113
3114 hldata = ancmap[(socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT)]
3115 self.assertEqual(len(hldata), SIZEOF_INT)
3116 a = array.array("i")
Nadeem Vawda3d1706f2011-08-22 09:46:56 +02003117 a.frombytes(hldata)
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003118 self.assertGreaterEqual(a[0], 0)
3119 self.assertLessEqual(a[0], maxhop)
3120
3121 @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
3122 "IPV6_RECVTCLASS", "IPV6_TCLASS")
3123 def testRecvTrafficClassAndHopLimit(self):
3124 # Test receiving traffic class and hop limit as ancillary data.
3125 self.checkTrafficClassAndHopLimit(ancbufsize=10240)
3126
3127 @testRecvTrafficClassAndHopLimit.client_skip
3128 def _testRecvTrafficClassAndHopLimit(self):
3129 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3130 self.sendToServer(MSG)
3131
3132 @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
3133 "IPV6_RECVTCLASS", "IPV6_TCLASS")
3134 def testRecvTrafficClassAndHopLimitCMSG_SPACE(self):
3135 # Test receiving traffic class and hop limit, using
3136 # CMSG_SPACE() to calculate buffer size.
3137 self.checkTrafficClassAndHopLimit(
3138 ancbufsize=socket.CMSG_SPACE(SIZEOF_INT) * 2)
3139
3140 @testRecvTrafficClassAndHopLimitCMSG_SPACE.client_skip
3141 def _testRecvTrafficClassAndHopLimitCMSG_SPACE(self):
3142 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3143 self.sendToServer(MSG)
3144
3145 @requireAttrs(socket.socket, "sendmsg")
3146 @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
3147 "IPV6_RECVTCLASS", "IPV6_TCLASS")
3148 def testSetTrafficClassAndHopLimit(self):
3149 # Test setting traffic class and hop limit on outgoing packet,
3150 # and receiving them at the other end.
3151 self.checkTrafficClassAndHopLimit(ancbufsize=10240,
3152 maxhop=self.hop_limit)
3153
3154 @testSetTrafficClassAndHopLimit.client_skip
3155 def _testSetTrafficClassAndHopLimit(self):
3156 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3157 self.assertEqual(
3158 self.sendmsgToServer([MSG],
3159 [(socket.IPPROTO_IPV6, socket.IPV6_TCLASS,
3160 array.array("i", [self.traffic_class])),
3161 (socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT,
3162 array.array("i", [self.hop_limit]))]),
3163 len(MSG))
3164
3165 @requireAttrs(socket.socket, "sendmsg")
3166 @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
3167 "IPV6_RECVTCLASS", "IPV6_TCLASS")
3168 def testOddCmsgSize(self):
3169 # Try to send ancillary data with first item one byte too
3170 # long. Fall back to sending with correct size if this fails,
3171 # and check that second item was handled correctly.
3172 self.checkTrafficClassAndHopLimit(ancbufsize=10240,
3173 maxhop=self.hop_limit)
3174
3175 @testOddCmsgSize.client_skip
3176 def _testOddCmsgSize(self):
3177 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3178 try:
3179 nbytes = self.sendmsgToServer(
3180 [MSG],
3181 [(socket.IPPROTO_IPV6, socket.IPV6_TCLASS,
Nadeem Vawda3d1706f2011-08-22 09:46:56 +02003182 array.array("i", [self.traffic_class]).tobytes() + b"\x00"),
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003183 (socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT,
3184 array.array("i", [self.hop_limit]))])
Andrew Svetlov0832af62012-12-18 23:10:48 +02003185 except OSError as e:
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003186 self.assertIsInstance(e.errno, int)
3187 nbytes = self.sendmsgToServer(
3188 [MSG],
3189 [(socket.IPPROTO_IPV6, socket.IPV6_TCLASS,
3190 array.array("i", [self.traffic_class])),
3191 (socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT,
3192 array.array("i", [self.hop_limit]))])
3193 self.assertEqual(nbytes, len(MSG))
3194
3195 # Tests for proper handling of truncated ancillary data
3196
3197 def checkHopLimitTruncatedHeader(self, ancbufsize, ignoreflags=0):
3198 # Receive hop limit into ancbufsize bytes of ancillary data
3199 # space, which should be too small to contain the ancillary
3200 # data header (if ancbufsize is None, pass no second argument
3201 # to recvmsg()). Check that data is MSG, MSG_CTRUNC is set
3202 # (unless included in ignoreflags), and no ancillary data is
3203 # returned.
3204 self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
3205 socket.IPV6_RECVHOPLIMIT, 1)
3206 self.misc_event.set()
3207 args = () if ancbufsize is None else (ancbufsize,)
3208 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
3209 len(MSG), *args)
3210
3211 self.assertEqual(msg, MSG)
3212 self.checkRecvmsgAddress(addr, self.cli_addr)
3213 self.assertEqual(ancdata, [])
3214 self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC,
3215 ignore=ignoreflags)
3216
3217 @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
3218 def testCmsgTruncNoBufSize(self):
3219 # Check that no ancillary data is received when no ancillary
3220 # buffer size is provided.
3221 self.checkHopLimitTruncatedHeader(ancbufsize=None,
3222 # BSD seems to set
3223 # MSG_CTRUNC only if an item
3224 # has been partially
3225 # received.
3226 ignoreflags=socket.MSG_CTRUNC)
3227
3228 @testCmsgTruncNoBufSize.client_skip
3229 def _testCmsgTruncNoBufSize(self):
3230 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3231 self.sendToServer(MSG)
3232
3233 @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
3234 def testSingleCmsgTrunc0(self):
3235 # Check that no ancillary data is received when ancillary
3236 # buffer size is zero.
3237 self.checkHopLimitTruncatedHeader(ancbufsize=0,
3238 ignoreflags=socket.MSG_CTRUNC)
3239
3240 @testSingleCmsgTrunc0.client_skip
3241 def _testSingleCmsgTrunc0(self):
3242 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3243 self.sendToServer(MSG)
3244
3245 # Check that no ancillary data is returned for various non-zero
3246 # (but still too small) buffer sizes.
3247
3248 @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
3249 def testSingleCmsgTrunc1(self):
3250 self.checkHopLimitTruncatedHeader(ancbufsize=1)
3251
3252 @testSingleCmsgTrunc1.client_skip
3253 def _testSingleCmsgTrunc1(self):
3254 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3255 self.sendToServer(MSG)
3256
3257 @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
3258 def testSingleCmsgTrunc2Int(self):
3259 self.checkHopLimitTruncatedHeader(ancbufsize=2 * SIZEOF_INT)
3260
3261 @testSingleCmsgTrunc2Int.client_skip
3262 def _testSingleCmsgTrunc2Int(self):
3263 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3264 self.sendToServer(MSG)
3265
3266 @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
3267 def testSingleCmsgTruncLen0Minus1(self):
3268 self.checkHopLimitTruncatedHeader(ancbufsize=socket.CMSG_LEN(0) - 1)
3269
3270 @testSingleCmsgTruncLen0Minus1.client_skip
3271 def _testSingleCmsgTruncLen0Minus1(self):
3272 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3273 self.sendToServer(MSG)
3274
3275 @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
3276 def testSingleCmsgTruncInData(self):
3277 # Test truncation of a control message inside its associated
3278 # data. The message may be returned with its data truncated,
3279 # or not returned at all.
3280 self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
3281 socket.IPV6_RECVHOPLIMIT, 1)
3282 self.misc_event.set()
3283 msg, ancdata, flags, addr = self.doRecvmsg(
3284 self.serv_sock, len(MSG), socket.CMSG_LEN(SIZEOF_INT) - 1)
3285
3286 self.assertEqual(msg, MSG)
3287 self.checkRecvmsgAddress(addr, self.cli_addr)
3288 self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC)
3289
3290 self.assertLessEqual(len(ancdata), 1)
3291 if ancdata:
3292 cmsg_level, cmsg_type, cmsg_data = ancdata[0]
3293 self.assertEqual(cmsg_level, socket.IPPROTO_IPV6)
3294 self.assertEqual(cmsg_type, socket.IPV6_HOPLIMIT)
3295 self.assertLess(len(cmsg_data), SIZEOF_INT)
3296
3297 @testSingleCmsgTruncInData.client_skip
3298 def _testSingleCmsgTruncInData(self):
3299 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3300 self.sendToServer(MSG)
3301
3302 def checkTruncatedSecondHeader(self, ancbufsize, ignoreflags=0):
3303 # Receive traffic class and hop limit into ancbufsize bytes of
3304 # ancillary data space, which should be large enough to
3305 # contain the first item, but too small to contain the header
3306 # of the second. Check that data is MSG, MSG_CTRUNC is set
3307 # (unless included in ignoreflags), and only one ancillary
3308 # data item is returned.
3309 self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
3310 socket.IPV6_RECVHOPLIMIT, 1)
3311 self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
3312 socket.IPV6_RECVTCLASS, 1)
3313 self.misc_event.set()
3314 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
3315 len(MSG), ancbufsize)
3316
3317 self.assertEqual(msg, MSG)
3318 self.checkRecvmsgAddress(addr, self.cli_addr)
3319 self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC,
3320 ignore=ignoreflags)
3321
3322 self.assertEqual(len(ancdata), 1)
3323 cmsg_level, cmsg_type, cmsg_data = ancdata[0]
3324 self.assertEqual(cmsg_level, socket.IPPROTO_IPV6)
3325 self.assertIn(cmsg_type, {socket.IPV6_TCLASS, socket.IPV6_HOPLIMIT})
3326 self.assertEqual(len(cmsg_data), SIZEOF_INT)
3327 a = array.array("i")
Nadeem Vawda3d1706f2011-08-22 09:46:56 +02003328 a.frombytes(cmsg_data)
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003329 self.assertGreaterEqual(a[0], 0)
3330 self.assertLessEqual(a[0], 255)
3331
3332 # Try the above test with various buffer sizes.
3333
3334 @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
3335 "IPV6_RECVTCLASS", "IPV6_TCLASS")
3336 def testSecondCmsgTrunc0(self):
3337 self.checkTruncatedSecondHeader(socket.CMSG_SPACE(SIZEOF_INT),
3338 ignoreflags=socket.MSG_CTRUNC)
3339
3340 @testSecondCmsgTrunc0.client_skip
3341 def _testSecondCmsgTrunc0(self):
3342 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3343 self.sendToServer(MSG)
3344
3345 @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
3346 "IPV6_RECVTCLASS", "IPV6_TCLASS")
3347 def testSecondCmsgTrunc1(self):
3348 self.checkTruncatedSecondHeader(socket.CMSG_SPACE(SIZEOF_INT) + 1)
3349
3350 @testSecondCmsgTrunc1.client_skip
3351 def _testSecondCmsgTrunc1(self):
3352 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3353 self.sendToServer(MSG)
3354
3355 @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
3356 "IPV6_RECVTCLASS", "IPV6_TCLASS")
3357 def testSecondCmsgTrunc2Int(self):
3358 self.checkTruncatedSecondHeader(socket.CMSG_SPACE(SIZEOF_INT) +
3359 2 * SIZEOF_INT)
3360
3361 @testSecondCmsgTrunc2Int.client_skip
3362 def _testSecondCmsgTrunc2Int(self):
3363 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3364 self.sendToServer(MSG)
3365
3366 @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
3367 "IPV6_RECVTCLASS", "IPV6_TCLASS")
3368 def testSecondCmsgTruncLen0Minus1(self):
3369 self.checkTruncatedSecondHeader(socket.CMSG_SPACE(SIZEOF_INT) +
3370 socket.CMSG_LEN(0) - 1)
3371
3372 @testSecondCmsgTruncLen0Minus1.client_skip
3373 def _testSecondCmsgTruncLen0Minus1(self):
3374 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3375 self.sendToServer(MSG)
3376
3377 @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
3378 "IPV6_RECVTCLASS", "IPV6_TCLASS")
3379 def testSecomdCmsgTruncInData(self):
3380 # Test truncation of the second of two control messages inside
3381 # its associated data.
3382 self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
3383 socket.IPV6_RECVHOPLIMIT, 1)
3384 self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
3385 socket.IPV6_RECVTCLASS, 1)
3386 self.misc_event.set()
3387 msg, ancdata, flags, addr = self.doRecvmsg(
3388 self.serv_sock, len(MSG),
3389 socket.CMSG_SPACE(SIZEOF_INT) + socket.CMSG_LEN(SIZEOF_INT) - 1)
3390
3391 self.assertEqual(msg, MSG)
3392 self.checkRecvmsgAddress(addr, self.cli_addr)
3393 self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC)
3394
3395 cmsg_types = {socket.IPV6_TCLASS, socket.IPV6_HOPLIMIT}
3396
3397 cmsg_level, cmsg_type, cmsg_data = ancdata.pop(0)
3398 self.assertEqual(cmsg_level, socket.IPPROTO_IPV6)
3399 cmsg_types.remove(cmsg_type)
3400 self.assertEqual(len(cmsg_data), SIZEOF_INT)
3401 a = array.array("i")
Nadeem Vawda3d1706f2011-08-22 09:46:56 +02003402 a.frombytes(cmsg_data)
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003403 self.assertGreaterEqual(a[0], 0)
3404 self.assertLessEqual(a[0], 255)
3405
3406 if ancdata:
3407 cmsg_level, cmsg_type, cmsg_data = ancdata.pop(0)
3408 self.assertEqual(cmsg_level, socket.IPPROTO_IPV6)
3409 cmsg_types.remove(cmsg_type)
3410 self.assertLess(len(cmsg_data), SIZEOF_INT)
3411
3412 self.assertEqual(ancdata, [])
3413
3414 @testSecomdCmsgTruncInData.client_skip
3415 def _testSecomdCmsgTruncInData(self):
3416 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3417 self.sendToServer(MSG)
3418
3419
3420# Derive concrete test classes for different socket types.
3421
3422class SendrecvmsgUDPTestBase(SendrecvmsgDgramFlagsBase,
3423 SendrecvmsgConnectionlessBase,
3424 ThreadedSocketTestMixin, UDPTestBase):
3425 pass
3426
3427@requireAttrs(socket.socket, "sendmsg")
3428@unittest.skipUnless(thread, 'Threading required for this test.')
3429class SendmsgUDPTest(SendmsgConnectionlessTests, SendrecvmsgUDPTestBase):
3430 pass
3431
3432@requireAttrs(socket.socket, "recvmsg")
3433@unittest.skipUnless(thread, 'Threading required for this test.')
3434class RecvmsgUDPTest(RecvmsgTests, SendrecvmsgUDPTestBase):
3435 pass
3436
3437@requireAttrs(socket.socket, "recvmsg_into")
3438@unittest.skipUnless(thread, 'Threading required for this test.')
3439class RecvmsgIntoUDPTest(RecvmsgIntoTests, SendrecvmsgUDPTestBase):
3440 pass
3441
3442
3443class SendrecvmsgUDP6TestBase(SendrecvmsgDgramFlagsBase,
3444 SendrecvmsgConnectionlessBase,
3445 ThreadedSocketTestMixin, UDP6TestBase):
Charles-François Natali37114bb2013-07-09 19:15:43 +02003446
3447 def checkRecvmsgAddress(self, addr1, addr2):
3448 # Called to compare the received address with the address of
3449 # the peer, ignoring scope ID
3450 self.assertEqual(addr1[:-1], addr2[:-1])
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003451
3452@requireAttrs(socket.socket, "sendmsg")
Ross Lagerwall8d459f02012-07-08 09:53:57 +02003453@unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.')
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003454@requireSocket("AF_INET6", "SOCK_DGRAM")
3455@unittest.skipUnless(thread, 'Threading required for this test.')
3456class SendmsgUDP6Test(SendmsgConnectionlessTests, SendrecvmsgUDP6TestBase):
3457 pass
3458
3459@requireAttrs(socket.socket, "recvmsg")
Ross Lagerwall8d459f02012-07-08 09:53:57 +02003460@unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.')
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003461@requireSocket("AF_INET6", "SOCK_DGRAM")
3462@unittest.skipUnless(thread, 'Threading required for this test.')
3463class RecvmsgUDP6Test(RecvmsgTests, SendrecvmsgUDP6TestBase):
3464 pass
3465
3466@requireAttrs(socket.socket, "recvmsg_into")
Ross Lagerwall8d459f02012-07-08 09:53:57 +02003467@unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.')
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003468@requireSocket("AF_INET6", "SOCK_DGRAM")
3469@unittest.skipUnless(thread, 'Threading required for this test.')
3470class RecvmsgIntoUDP6Test(RecvmsgIntoTests, SendrecvmsgUDP6TestBase):
3471 pass
3472
3473@requireAttrs(socket.socket, "recvmsg")
Ross Lagerwall8d459f02012-07-08 09:53:57 +02003474@unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.')
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003475@requireAttrs(socket, "IPPROTO_IPV6")
3476@requireSocket("AF_INET6", "SOCK_DGRAM")
3477@unittest.skipUnless(thread, 'Threading required for this test.')
3478class RecvmsgRFC3542AncillaryUDP6Test(RFC3542AncillaryTest,
3479 SendrecvmsgUDP6TestBase):
3480 pass
3481
3482@requireAttrs(socket.socket, "recvmsg_into")
Ross Lagerwall8d459f02012-07-08 09:53:57 +02003483@unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.')
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003484@requireAttrs(socket, "IPPROTO_IPV6")
3485@requireSocket("AF_INET6", "SOCK_DGRAM")
3486@unittest.skipUnless(thread, 'Threading required for this test.')
3487class RecvmsgIntoRFC3542AncillaryUDP6Test(RecvmsgIntoMixin,
3488 RFC3542AncillaryTest,
3489 SendrecvmsgUDP6TestBase):
3490 pass
3491
3492
3493class SendrecvmsgTCPTestBase(SendrecvmsgConnectedBase,
3494 ConnectedStreamTestMixin, TCPTestBase):
3495 pass
3496
3497@requireAttrs(socket.socket, "sendmsg")
3498@unittest.skipUnless(thread, 'Threading required for this test.')
3499class SendmsgTCPTest(SendmsgStreamTests, SendrecvmsgTCPTestBase):
3500 pass
3501
3502@requireAttrs(socket.socket, "recvmsg")
3503@unittest.skipUnless(thread, 'Threading required for this test.')
3504class RecvmsgTCPTest(RecvmsgTests, RecvmsgGenericStreamTests,
3505 SendrecvmsgTCPTestBase):
3506 pass
3507
3508@requireAttrs(socket.socket, "recvmsg_into")
3509@unittest.skipUnless(thread, 'Threading required for this test.')
3510class RecvmsgIntoTCPTest(RecvmsgIntoTests, RecvmsgGenericStreamTests,
3511 SendrecvmsgTCPTestBase):
3512 pass
3513
3514
3515class SendrecvmsgSCTPStreamTestBase(SendrecvmsgSCTPFlagsBase,
3516 SendrecvmsgConnectedBase,
3517 ConnectedStreamTestMixin, SCTPStreamBase):
3518 pass
3519
3520@requireAttrs(socket.socket, "sendmsg")
3521@requireSocket("AF_INET", "SOCK_STREAM", "IPPROTO_SCTP")
3522@unittest.skipUnless(thread, 'Threading required for this test.')
3523class SendmsgSCTPStreamTest(SendmsgStreamTests, SendrecvmsgSCTPStreamTestBase):
3524 pass
3525
3526@requireAttrs(socket.socket, "recvmsg")
3527@requireSocket("AF_INET", "SOCK_STREAM", "IPPROTO_SCTP")
3528@unittest.skipUnless(thread, 'Threading required for this test.')
3529class RecvmsgSCTPStreamTest(RecvmsgTests, RecvmsgGenericStreamTests,
3530 SendrecvmsgSCTPStreamTestBase):
Antoine Pitrou92f8b002012-12-16 16:40:04 +01003531
3532 def testRecvmsgEOF(self):
3533 try:
3534 super(RecvmsgSCTPStreamTest, self).testRecvmsgEOF()
3535 except OSError as e:
3536 if e.errno != errno.ENOTCONN:
3537 raise
3538 self.skipTest("sporadic ENOTCONN (kernel issue?) - see issue #13876")
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003539
3540@requireAttrs(socket.socket, "recvmsg_into")
3541@requireSocket("AF_INET", "SOCK_STREAM", "IPPROTO_SCTP")
3542@unittest.skipUnless(thread, 'Threading required for this test.')
3543class RecvmsgIntoSCTPStreamTest(RecvmsgIntoTests, RecvmsgGenericStreamTests,
3544 SendrecvmsgSCTPStreamTestBase):
Antoine Pitroud5a070f2012-12-18 23:44:36 +01003545
3546 def testRecvmsgEOF(self):
3547 try:
3548 super(RecvmsgIntoSCTPStreamTest, self).testRecvmsgEOF()
3549 except OSError as e:
3550 if e.errno != errno.ENOTCONN:
3551 raise
3552 self.skipTest("sporadic ENOTCONN (kernel issue?) - see issue #13876")
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003553
3554
3555class SendrecvmsgUnixStreamTestBase(SendrecvmsgConnectedBase,
3556 ConnectedStreamTestMixin, UnixStreamBase):
3557 pass
3558
3559@requireAttrs(socket.socket, "sendmsg")
3560@requireAttrs(socket, "AF_UNIX")
3561@unittest.skipUnless(thread, 'Threading required for this test.')
3562class SendmsgUnixStreamTest(SendmsgStreamTests, SendrecvmsgUnixStreamTestBase):
3563 pass
3564
3565@requireAttrs(socket.socket, "recvmsg")
3566@requireAttrs(socket, "AF_UNIX")
3567@unittest.skipUnless(thread, 'Threading required for this test.')
3568class RecvmsgUnixStreamTest(RecvmsgTests, RecvmsgGenericStreamTests,
3569 SendrecvmsgUnixStreamTestBase):
3570 pass
3571
3572@requireAttrs(socket.socket, "recvmsg_into")
3573@requireAttrs(socket, "AF_UNIX")
3574@unittest.skipUnless(thread, 'Threading required for this test.')
3575class RecvmsgIntoUnixStreamTest(RecvmsgIntoTests, RecvmsgGenericStreamTests,
3576 SendrecvmsgUnixStreamTestBase):
3577 pass
3578
3579@requireAttrs(socket.socket, "sendmsg", "recvmsg")
3580@requireAttrs(socket, "AF_UNIX", "SOL_SOCKET", "SCM_RIGHTS")
3581@unittest.skipUnless(thread, 'Threading required for this test.')
3582class RecvmsgSCMRightsStreamTest(SCMRightsTest, SendrecvmsgUnixStreamTestBase):
3583 pass
3584
3585@requireAttrs(socket.socket, "sendmsg", "recvmsg_into")
3586@requireAttrs(socket, "AF_UNIX", "SOL_SOCKET", "SCM_RIGHTS")
3587@unittest.skipUnless(thread, 'Threading required for this test.')
3588class RecvmsgIntoSCMRightsStreamTest(RecvmsgIntoMixin, SCMRightsTest,
3589 SendrecvmsgUnixStreamTestBase):
3590 pass
3591
3592
3593# Test interrupting the interruptible send/receive methods with a
3594# signal when a timeout is set. These tests avoid having multiple
3595# threads alive during the test so that the OS cannot deliver the
3596# signal to the wrong one.
3597
3598class InterruptedTimeoutBase(unittest.TestCase):
3599 # Base class for interrupted send/receive tests. Installs an
3600 # empty handler for SIGALRM and removes it on teardown, along with
3601 # any scheduled alarms.
3602
3603 def setUp(self):
3604 super().setUp()
3605 orig_alrm_handler = signal.signal(signal.SIGALRM,
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003606 lambda signum, frame: 1 / 0)
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003607 self.addCleanup(signal.signal, signal.SIGALRM, orig_alrm_handler)
3608 self.addCleanup(self.setAlarm, 0)
3609
3610 # Timeout for socket operations
3611 timeout = 4.0
3612
3613 # Provide setAlarm() method to schedule delivery of SIGALRM after
3614 # given number of seconds, or cancel it if zero, and an
3615 # appropriate time value to use. Use setitimer() if available.
3616 if hasattr(signal, "setitimer"):
3617 alarm_time = 0.05
3618
3619 def setAlarm(self, seconds):
3620 signal.setitimer(signal.ITIMER_REAL, seconds)
3621 else:
3622 # Old systems may deliver the alarm up to one second early
3623 alarm_time = 2
3624
3625 def setAlarm(self, seconds):
3626 signal.alarm(seconds)
3627
3628
3629# Require siginterrupt() in order to ensure that system calls are
3630# interrupted by default.
3631@requireAttrs(signal, "siginterrupt")
3632@unittest.skipUnless(hasattr(signal, "alarm") or hasattr(signal, "setitimer"),
3633 "Don't have signal.alarm or signal.setitimer")
3634class InterruptedRecvTimeoutTest(InterruptedTimeoutBase, UDPTestBase):
3635 # Test interrupting the recv*() methods with signals when a
3636 # timeout is set.
3637
3638 def setUp(self):
3639 super().setUp()
3640 self.serv.settimeout(self.timeout)
3641
3642 def checkInterruptedRecv(self, func, *args, **kwargs):
Charles-François Natali26dd5ed2015-02-07 13:29:15 +00003643 # Check that func(*args, **kwargs) raises
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003644 # errno of EINTR when interrupted by a signal.
3645 self.setAlarm(self.alarm_time)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003646 with self.assertRaises(ZeroDivisionError) as cm:
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003647 func(*args, **kwargs)
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003648
3649 def testInterruptedRecvTimeout(self):
3650 self.checkInterruptedRecv(self.serv.recv, 1024)
3651
3652 def testInterruptedRecvIntoTimeout(self):
3653 self.checkInterruptedRecv(self.serv.recv_into, bytearray(1024))
3654
3655 def testInterruptedRecvfromTimeout(self):
3656 self.checkInterruptedRecv(self.serv.recvfrom, 1024)
3657
3658 def testInterruptedRecvfromIntoTimeout(self):
3659 self.checkInterruptedRecv(self.serv.recvfrom_into, bytearray(1024))
3660
3661 @requireAttrs(socket.socket, "recvmsg")
3662 def testInterruptedRecvmsgTimeout(self):
3663 self.checkInterruptedRecv(self.serv.recvmsg, 1024)
3664
3665 @requireAttrs(socket.socket, "recvmsg_into")
3666 def testInterruptedRecvmsgIntoTimeout(self):
3667 self.checkInterruptedRecv(self.serv.recvmsg_into, [bytearray(1024)])
3668
3669
3670# Require siginterrupt() in order to ensure that system calls are
3671# interrupted by default.
3672@requireAttrs(signal, "siginterrupt")
3673@unittest.skipUnless(hasattr(signal, "alarm") or hasattr(signal, "setitimer"),
3674 "Don't have signal.alarm or signal.setitimer")
3675@unittest.skipUnless(thread, 'Threading required for this test.')
3676class InterruptedSendTimeoutTest(InterruptedTimeoutBase,
3677 ThreadSafeCleanupTestCase,
3678 SocketListeningTestMixin, TCPTestBase):
3679 # Test interrupting the interruptible send*() methods with signals
3680 # when a timeout is set.
3681
3682 def setUp(self):
3683 super().setUp()
3684 self.serv_conn = self.newSocket()
3685 self.addCleanup(self.serv_conn.close)
3686 # Use a thread to complete the connection, but wait for it to
3687 # terminate before running the test, so that there is only one
3688 # thread to accept the signal.
3689 cli_thread = threading.Thread(target=self.doConnect)
3690 cli_thread.start()
3691 self.cli_conn, addr = self.serv.accept()
3692 self.addCleanup(self.cli_conn.close)
3693 cli_thread.join()
3694 self.serv_conn.settimeout(self.timeout)
3695
3696 def doConnect(self):
3697 self.serv_conn.connect(self.serv_addr)
3698
3699 def checkInterruptedSend(self, func, *args, **kwargs):
3700 # Check that func(*args, **kwargs), run in a loop, raises
Andrew Svetlov0832af62012-12-18 23:10:48 +02003701 # OSError with an errno of EINTR when interrupted by a
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003702 # signal.
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003703 with self.assertRaises(ZeroDivisionError) as cm:
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003704 while True:
3705 self.setAlarm(self.alarm_time)
3706 func(*args, **kwargs)
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003707
Ned Deilyc5640382014-02-03 13:58:31 -08003708 # Issue #12958: The following tests have problems on OS X prior to 10.7
3709 @support.requires_mac_ver(10, 7)
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003710 def testInterruptedSendTimeout(self):
3711 self.checkInterruptedSend(self.serv_conn.send, b"a"*512)
3712
Ned Deilyc5640382014-02-03 13:58:31 -08003713 @support.requires_mac_ver(10, 7)
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003714 def testInterruptedSendtoTimeout(self):
3715 # Passing an actual address here as Python's wrapper for
3716 # sendto() doesn't allow passing a zero-length one; POSIX
3717 # requires that the address is ignored since the socket is
3718 # connection-mode, however.
3719 self.checkInterruptedSend(self.serv_conn.sendto, b"a"*512,
3720 self.serv_addr)
3721
Ned Deilyc5640382014-02-03 13:58:31 -08003722 @support.requires_mac_ver(10, 7)
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003723 @requireAttrs(socket.socket, "sendmsg")
3724 def testInterruptedSendmsgTimeout(self):
3725 self.checkInterruptedSend(self.serv_conn.sendmsg, [b"a"*512])
3726
3727
Victor Stinner45df8202010-04-28 22:31:17 +00003728@unittest.skipUnless(thread, 'Threading required for this test.')
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003729class TCPCloserTest(ThreadedTCPSocketTest):
3730
3731 def testClose(self):
3732 conn, addr = self.serv.accept()
3733 conn.close()
3734
3735 sd = self.cli
3736 read, write, err = select.select([sd], [], [], 1.0)
3737 self.assertEqual(read, [sd])
Guido van Rossum7d0a8262007-05-21 23:13:11 +00003738 self.assertEqual(sd.recv(1), b'')
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003739
Jeremy Hylton5accbdb2007-08-03 20:40:09 +00003740 # Calling close() many times should be safe.
3741 conn.close()
3742 conn.close()
3743
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003744 def _testClose(self):
Christian Heimes5e696852008-04-09 08:37:03 +00003745 self.cli.connect((HOST, self.port))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003746 time.sleep(1.0)
3747
Victor Stinner45df8202010-04-28 22:31:17 +00003748@unittest.skipUnless(thread, 'Threading required for this test.')
Dave Cole331708b2004-08-09 04:51:41 +00003749class BasicSocketPairTest(SocketPairTest):
3750
3751 def __init__(self, methodName='runTest'):
3752 SocketPairTest.__init__(self, methodName=methodName)
3753
Antoine Pitrou2e55fec2010-09-14 21:24:25 +00003754 def _check_defaults(self, sock):
3755 self.assertIsInstance(sock, socket.socket)
3756 if hasattr(socket, 'AF_UNIX'):
3757 self.assertEqual(sock.family, socket.AF_UNIX)
3758 else:
3759 self.assertEqual(sock.family, socket.AF_INET)
3760 self.assertEqual(sock.type, socket.SOCK_STREAM)
3761 self.assertEqual(sock.proto, 0)
3762
Antoine Pitrou9e0b8642010-09-14 18:00:02 +00003763 def _testDefaults(self):
Antoine Pitrou2e55fec2010-09-14 21:24:25 +00003764 self._check_defaults(self.cli)
Antoine Pitrou9e0b8642010-09-14 18:00:02 +00003765
3766 def testDefaults(self):
Antoine Pitrou2e55fec2010-09-14 21:24:25 +00003767 self._check_defaults(self.serv)
Antoine Pitrou9e0b8642010-09-14 18:00:02 +00003768
Dave Cole331708b2004-08-09 04:51:41 +00003769 def testRecv(self):
3770 msg = self.serv.recv(1024)
3771 self.assertEqual(msg, MSG)
3772
3773 def _testRecv(self):
3774 self.cli.send(MSG)
3775
3776 def testSend(self):
3777 self.serv.send(MSG)
3778
3779 def _testSend(self):
3780 msg = self.cli.recv(1024)
3781 self.assertEqual(msg, MSG)
3782
Victor Stinner45df8202010-04-28 22:31:17 +00003783@unittest.skipUnless(thread, 'Threading required for this test.')
Guido van Rossum24e4af82002-06-12 19:18:08 +00003784class NonBlockingTCPTests(ThreadedTCPSocketTest):
3785
3786 def __init__(self, methodName='runTest'):
3787 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
3788
3789 def testSetBlocking(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00003790 # Testing whether set blocking works
Serhiy Storchaka45cb7f62013-01-15 11:08:30 +02003791 self.serv.setblocking(True)
3792 self.assertIsNone(self.serv.gettimeout())
3793 self.serv.setblocking(False)
3794 self.assertEqual(self.serv.gettimeout(), 0.0)
Guido van Rossum24e4af82002-06-12 19:18:08 +00003795 start = time.time()
3796 try:
3797 self.serv.accept()
Andrew Svetlov0832af62012-12-18 23:10:48 +02003798 except OSError:
Guido van Rossum24e4af82002-06-12 19:18:08 +00003799 pass
3800 end = time.time()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003801 self.assertTrue((end - start) < 1.0, "Error setting non-blocking mode.")
Guido van Rossum24e4af82002-06-12 19:18:08 +00003802
3803 def _testSetBlocking(self):
Barry Warsaw6870bba2001-03-23 17:40:16 +00003804 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +00003805
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02003806 @support.cpython_only
3807 def testSetBlocking_overflow(self):
3808 # Issue 15989
3809 import _testcapi
3810 if _testcapi.UINT_MAX >= _testcapi.ULONG_MAX:
3811 self.skipTest('needs UINT_MAX < ULONG_MAX')
3812 self.serv.setblocking(False)
3813 self.assertEqual(self.serv.gettimeout(), 0.0)
3814 self.serv.setblocking(_testcapi.UINT_MAX + 1)
3815 self.assertIsNone(self.serv.gettimeout())
3816
3817 _testSetBlocking_overflow = support.cpython_only(_testSetBlocking)
3818
Serhiy Storchaka43767632013-11-03 21:31:38 +02003819 @unittest.skipUnless(hasattr(socket, 'SOCK_NONBLOCK'),
3820 'test needs socket.SOCK_NONBLOCK')
3821 @support.requires_linux_version(2, 6, 28)
3822 def testInitNonBlocking(self):
3823 # reinit server socket
3824 self.serv.close()
3825 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM |
3826 socket.SOCK_NONBLOCK)
3827 self.port = support.bind_port(self.serv)
Charles-François Natali6e204602014-07-23 19:28:13 +01003828 self.serv.listen()
Serhiy Storchaka43767632013-11-03 21:31:38 +02003829 # actual testing
3830 start = time.time()
3831 try:
3832 self.serv.accept()
3833 except OSError:
Antoine Pitroub1c54962010-10-14 15:05:38 +00003834 pass
Serhiy Storchaka43767632013-11-03 21:31:38 +02003835 end = time.time()
3836 self.assertTrue((end - start) < 1.0, "Error creating with non-blocking mode.")
3837
3838 def _testInitNonBlocking(self):
3839 pass
Antoine Pitroub1c54962010-10-14 15:05:38 +00003840
Antoine Pitrou600232b2011-01-05 21:03:42 +00003841 def testInheritFlags(self):
3842 # Issue #7995: when calling accept() on a listening socket with a
3843 # timeout, the resulting socket should not be non-blocking.
3844 self.serv.settimeout(10)
3845 try:
3846 conn, addr = self.serv.accept()
3847 message = conn.recv(len(MSG))
3848 finally:
3849 conn.close()
3850 self.serv.settimeout(None)
3851
3852 def _testInheritFlags(self):
3853 time.sleep(0.1)
3854 self.cli.connect((HOST, self.port))
3855 time.sleep(0.5)
3856 self.cli.send(MSG)
3857
Guido van Rossum24e4af82002-06-12 19:18:08 +00003858 def testAccept(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00003859 # Testing non-blocking accept
Guido van Rossum24e4af82002-06-12 19:18:08 +00003860 self.serv.setblocking(0)
Guido van Rossum41360a41998-03-26 19:42:58 +00003861 try:
Guido van Rossum24e4af82002-06-12 19:18:08 +00003862 conn, addr = self.serv.accept()
Andrew Svetlov0832af62012-12-18 23:10:48 +02003863 except OSError:
Guido van Rossum24e4af82002-06-12 19:18:08 +00003864 pass
3865 else:
3866 self.fail("Error trying to do non-blocking accept.")
3867 read, write, err = select.select([self.serv], [], [])
3868 if self.serv in read:
3869 conn, addr = self.serv.accept()
Benjamin Petersond9dbf492015-10-24 20:06:04 -07003870 self.assertIsNone(conn.gettimeout())
Brian Curtin21ebbb72010-11-02 02:07:09 +00003871 conn.close()
Guido van Rossum24e4af82002-06-12 19:18:08 +00003872 else:
3873 self.fail("Error trying to do accept after select.")
Guido van Rossum67f7a382002-06-06 21:08:16 +00003874
Guido van Rossum24e4af82002-06-12 19:18:08 +00003875 def _testAccept(self):
Guido van Rossumb6cc7d22002-07-19 12:46:46 +00003876 time.sleep(0.1)
Christian Heimes5e696852008-04-09 08:37:03 +00003877 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +00003878
3879 def testConnect(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00003880 # Testing non-blocking connect
Guido van Rossum24e4af82002-06-12 19:18:08 +00003881 conn, addr = self.serv.accept()
Brian Curtin21ebbb72010-11-02 02:07:09 +00003882 conn.close()
Guido van Rossum24e4af82002-06-12 19:18:08 +00003883
3884 def _testConnect(self):
Guido van Rossum7b8bac12002-06-13 16:07:04 +00003885 self.cli.settimeout(10)
Christian Heimes5e696852008-04-09 08:37:03 +00003886 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +00003887
3888 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00003889 # Testing non-blocking recv
Guido van Rossum24e4af82002-06-12 19:18:08 +00003890 conn, addr = self.serv.accept()
3891 conn.setblocking(0)
3892 try:
3893 msg = conn.recv(len(MSG))
Andrew Svetlov0832af62012-12-18 23:10:48 +02003894 except OSError:
Guido van Rossum24e4af82002-06-12 19:18:08 +00003895 pass
3896 else:
3897 self.fail("Error trying to do non-blocking recv.")
3898 read, write, err = select.select([conn], [], [])
3899 if conn in read:
3900 msg = conn.recv(len(MSG))
Brian Curtin21ebbb72010-11-02 02:07:09 +00003901 conn.close()
Guido van Rossum76489682002-06-12 20:38:30 +00003902 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +00003903 else:
3904 self.fail("Error during select call to non-blocking socket.")
3905
3906 def _testRecv(self):
Christian Heimes5e696852008-04-09 08:37:03 +00003907 self.cli.connect((HOST, self.port))
Guido van Rossumb6cc7d22002-07-19 12:46:46 +00003908 time.sleep(0.1)
Guido van Rossum24e4af82002-06-12 19:18:08 +00003909 self.cli.send(MSG)
3910
Victor Stinner45df8202010-04-28 22:31:17 +00003911@unittest.skipUnless(thread, 'Threading required for this test.')
Guido van Rossum24e4af82002-06-12 19:18:08 +00003912class FileObjectClassTestCase(SocketConnectedTest):
Jeremy Hylton5accbdb2007-08-03 20:40:09 +00003913 """Unit tests for the object returned by socket.makefile()
3914
Antoine Pitrou834bd812010-10-13 16:17:14 +00003915 self.read_file is the io object returned by makefile() on
Jeremy Hylton5accbdb2007-08-03 20:40:09 +00003916 the client connection. You can read from this file to
3917 get output from the server.
3918
Antoine Pitrou834bd812010-10-13 16:17:14 +00003919 self.write_file is the io object returned by makefile() on the
Jeremy Hylton5accbdb2007-08-03 20:40:09 +00003920 server connection. You can write to this file to send output
3921 to the client.
3922 """
Guido van Rossum24e4af82002-06-12 19:18:08 +00003923
Guido van Rossume9f66142002-08-07 15:46:19 +00003924 bufsize = -1 # Use default buffer size
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00003925 encoding = 'utf-8'
Antoine Pitrou834bd812010-10-13 16:17:14 +00003926 errors = 'strict'
3927 newline = None
3928
3929 read_mode = 'rb'
3930 read_msg = MSG
3931 write_mode = 'wb'
3932 write_msg = MSG
Guido van Rossume9f66142002-08-07 15:46:19 +00003933
Guido van Rossum24e4af82002-06-12 19:18:08 +00003934 def __init__(self, methodName='runTest'):
3935 SocketConnectedTest.__init__(self, methodName=methodName)
3936
3937 def setUp(self):
Antoine Pitrou98b46702010-09-18 22:59:00 +00003938 self.evt1, self.evt2, self.serv_finished, self.cli_finished = [
3939 threading.Event() for i in range(4)]
Guido van Rossum24e4af82002-06-12 19:18:08 +00003940 SocketConnectedTest.setUp(self)
Antoine Pitrou834bd812010-10-13 16:17:14 +00003941 self.read_file = self.cli_conn.makefile(
3942 self.read_mode, self.bufsize,
3943 encoding = self.encoding,
3944 errors = self.errors,
3945 newline = self.newline)
Guido van Rossum24e4af82002-06-12 19:18:08 +00003946
3947 def tearDown(self):
Antoine Pitrou98b46702010-09-18 22:59:00 +00003948 self.serv_finished.set()
Antoine Pitrou834bd812010-10-13 16:17:14 +00003949 self.read_file.close()
3950 self.assertTrue(self.read_file.closed)
3951 self.read_file = None
Guido van Rossum24e4af82002-06-12 19:18:08 +00003952 SocketConnectedTest.tearDown(self)
3953
3954 def clientSetUp(self):
3955 SocketConnectedTest.clientSetUp(self)
Antoine Pitrou834bd812010-10-13 16:17:14 +00003956 self.write_file = self.serv_conn.makefile(
3957 self.write_mode, self.bufsize,
3958 encoding = self.encoding,
3959 errors = self.errors,
3960 newline = self.newline)
Guido van Rossum24e4af82002-06-12 19:18:08 +00003961
3962 def clientTearDown(self):
Antoine Pitrou98b46702010-09-18 22:59:00 +00003963 self.cli_finished.set()
Antoine Pitrou834bd812010-10-13 16:17:14 +00003964 self.write_file.close()
3965 self.assertTrue(self.write_file.closed)
3966 self.write_file = None
Guido van Rossum24e4af82002-06-12 19:18:08 +00003967 SocketConnectedTest.clientTearDown(self)
3968
Antoine Pitrou68e5c042011-02-25 23:07:44 +00003969 def testReadAfterTimeout(self):
3970 # Issue #7322: A file object must disallow further reads
3971 # after a timeout has occurred.
3972 self.cli_conn.settimeout(1)
3973 self.read_file.read(3)
3974 # First read raises a timeout
3975 self.assertRaises(socket.timeout, self.read_file.read, 1)
3976 # Second read is disallowed
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02003977 with self.assertRaises(OSError) as ctx:
Antoine Pitrou68e5c042011-02-25 23:07:44 +00003978 self.read_file.read(1)
3979 self.assertIn("cannot read from timed out object", str(ctx.exception))
3980
3981 def _testReadAfterTimeout(self):
3982 self.write_file.write(self.write_msg[0:3])
3983 self.write_file.flush()
3984 self.serv_finished.wait()
3985
Guido van Rossum24e4af82002-06-12 19:18:08 +00003986 def testSmallRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00003987 # Performing small file read test
Antoine Pitrou834bd812010-10-13 16:17:14 +00003988 first_seg = self.read_file.read(len(self.read_msg)-3)
3989 second_seg = self.read_file.read(3)
Guido van Rossumab659962002-06-12 21:29:43 +00003990 msg = first_seg + second_seg
Antoine Pitrou834bd812010-10-13 16:17:14 +00003991 self.assertEqual(msg, self.read_msg)
Guido van Rossum24e4af82002-06-12 19:18:08 +00003992
3993 def _testSmallRead(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00003994 self.write_file.write(self.write_msg)
3995 self.write_file.flush()
Guido van Rossum24e4af82002-06-12 19:18:08 +00003996
Guido van Rossum8c943832002-08-08 01:00:28 +00003997 def testFullRead(self):
3998 # read until EOF
Antoine Pitrou834bd812010-10-13 16:17:14 +00003999 msg = self.read_file.read()
4000 self.assertEqual(msg, self.read_msg)
Guido van Rossum8c943832002-08-08 01:00:28 +00004001
4002 def _testFullRead(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00004003 self.write_file.write(self.write_msg)
4004 self.write_file.close()
Guido van Rossum8c943832002-08-08 01:00:28 +00004005
Guido van Rossum24e4af82002-06-12 19:18:08 +00004006 def testUnbufferedRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00004007 # Performing unbuffered file read test
Antoine Pitrou834bd812010-10-13 16:17:14 +00004008 buf = type(self.read_msg)()
Guido van Rossum24e4af82002-06-12 19:18:08 +00004009 while 1:
Antoine Pitrou834bd812010-10-13 16:17:14 +00004010 char = self.read_file.read(1)
Guido van Rossum8c943832002-08-08 01:00:28 +00004011 if not char:
Guido van Rossum24e4af82002-06-12 19:18:08 +00004012 break
Guido van Rossum8c943832002-08-08 01:00:28 +00004013 buf += char
Antoine Pitrou834bd812010-10-13 16:17:14 +00004014 self.assertEqual(buf, self.read_msg)
Guido van Rossum24e4af82002-06-12 19:18:08 +00004015
4016 def _testUnbufferedRead(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00004017 self.write_file.write(self.write_msg)
4018 self.write_file.flush()
Guido van Rossum24e4af82002-06-12 19:18:08 +00004019
4020 def testReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00004021 # Performing file readline test
Antoine Pitrou834bd812010-10-13 16:17:14 +00004022 line = self.read_file.readline()
4023 self.assertEqual(line, self.read_msg)
Guido van Rossum24e4af82002-06-12 19:18:08 +00004024
4025 def _testReadline(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00004026 self.write_file.write(self.write_msg)
4027 self.write_file.flush()
Guido van Rossum24e4af82002-06-12 19:18:08 +00004028
Jeremy Hylton5accbdb2007-08-03 20:40:09 +00004029 def testCloseAfterMakefile(self):
4030 # The file returned by makefile should keep the socket open.
4031 self.cli_conn.close()
4032 # read until EOF
Antoine Pitrou834bd812010-10-13 16:17:14 +00004033 msg = self.read_file.read()
4034 self.assertEqual(msg, self.read_msg)
Jeremy Hylton5accbdb2007-08-03 20:40:09 +00004035
4036 def _testCloseAfterMakefile(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00004037 self.write_file.write(self.write_msg)
4038 self.write_file.flush()
Jeremy Hylton5accbdb2007-08-03 20:40:09 +00004039
4040 def testMakefileAfterMakefileClose(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00004041 self.read_file.close()
Jeremy Hylton5accbdb2007-08-03 20:40:09 +00004042 msg = self.cli_conn.recv(len(MSG))
Antoine Pitrou834bd812010-10-13 16:17:14 +00004043 if isinstance(self.read_msg, str):
4044 msg = msg.decode()
4045 self.assertEqual(msg, self.read_msg)
Jeremy Hylton5accbdb2007-08-03 20:40:09 +00004046
4047 def _testMakefileAfterMakefileClose(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00004048 self.write_file.write(self.write_msg)
4049 self.write_file.flush()
Jeremy Hylton5accbdb2007-08-03 20:40:09 +00004050
Tim Peters116d83c2004-03-28 02:20:45 +00004051 def testClosedAttr(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00004052 self.assertTrue(not self.read_file.closed)
Tim Peters116d83c2004-03-28 02:20:45 +00004053
4054 def _testClosedAttr(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00004055 self.assertTrue(not self.write_file.closed)
Tim Peters116d83c2004-03-28 02:20:45 +00004056
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +00004057 def testAttributes(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00004058 self.assertEqual(self.read_file.mode, self.read_mode)
4059 self.assertEqual(self.read_file.name, self.cli_conn.fileno())
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +00004060
4061 def _testAttributes(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00004062 self.assertEqual(self.write_file.mode, self.write_mode)
4063 self.assertEqual(self.write_file.name, self.serv_conn.fileno())
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +00004064
Gregory P. Smithde3369f2009-01-12 04:50:11 +00004065 def testRealClose(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00004066 self.read_file.close()
4067 self.assertRaises(ValueError, self.read_file.fileno)
Gregory P. Smithde3369f2009-01-12 04:50:11 +00004068 self.cli_conn.close()
Andrew Svetlov0832af62012-12-18 23:10:48 +02004069 self.assertRaises(OSError, self.cli_conn.getsockname)
Gregory P. Smithde3369f2009-01-12 04:50:11 +00004070
4071 def _testRealClose(self):
4072 pass
4073
4074
Guido van Rossume9f66142002-08-07 15:46:19 +00004075class UnbufferedFileObjectClassTestCase(FileObjectClassTestCase):
4076
4077 """Repeat the tests from FileObjectClassTestCase with bufsize==0.
Tim Peters469cdad2002-08-08 20:19:19 +00004078
Guido van Rossume9f66142002-08-07 15:46:19 +00004079 In this case (and in this case only), it should be possible to
4080 create a file object, read a line from it, create another file
4081 object, read another line from it, without loss of data in the
Georg Brandl24420152008-05-26 16:32:26 +00004082 first file object's buffer. Note that http.client relies on this
Guido van Rossume9f66142002-08-07 15:46:19 +00004083 when reading multiple requests from the same socket."""
4084
4085 bufsize = 0 # Use unbuffered mode
4086
4087 def testUnbufferedReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00004088 # Read a line, create a new file object, read another line with it
Antoine Pitrou834bd812010-10-13 16:17:14 +00004089 line = self.read_file.readline() # first line
4090 self.assertEqual(line, b"A. " + self.write_msg) # first line
4091 self.read_file = self.cli_conn.makefile('rb', 0)
4092 line = self.read_file.readline() # second line
4093 self.assertEqual(line, b"B. " + self.write_msg) # second line
Guido van Rossume9f66142002-08-07 15:46:19 +00004094
4095 def _testUnbufferedReadline(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00004096 self.write_file.write(b"A. " + self.write_msg)
4097 self.write_file.write(b"B. " + self.write_msg)
4098 self.write_file.flush()
Guido van Rossume9f66142002-08-07 15:46:19 +00004099
Gregory P. Smithde3369f2009-01-12 04:50:11 +00004100 def testMakefileClose(self):
4101 # The file returned by makefile should keep the socket open...
4102 self.cli_conn.close()
4103 msg = self.cli_conn.recv(1024)
Antoine Pitrou834bd812010-10-13 16:17:14 +00004104 self.assertEqual(msg, self.read_msg)
Gregory P. Smithde3369f2009-01-12 04:50:11 +00004105 # ...until the file is itself closed
Antoine Pitrou834bd812010-10-13 16:17:14 +00004106 self.read_file.close()
Andrew Svetlov0832af62012-12-18 23:10:48 +02004107 self.assertRaises(OSError, self.cli_conn.recv, 1024)
Gregory P. Smithde3369f2009-01-12 04:50:11 +00004108
4109 def _testMakefileClose(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00004110 self.write_file.write(self.write_msg)
4111 self.write_file.flush()
Gregory P. Smithde3369f2009-01-12 04:50:11 +00004112
4113 def testMakefileCloseSocketDestroy(self):
4114 refcount_before = sys.getrefcount(self.cli_conn)
Antoine Pitrou834bd812010-10-13 16:17:14 +00004115 self.read_file.close()
Gregory P. Smithde3369f2009-01-12 04:50:11 +00004116 refcount_after = sys.getrefcount(self.cli_conn)
4117 self.assertEqual(refcount_before - 1, refcount_after)
4118
4119 def _testMakefileCloseSocketDestroy(self):
4120 pass
4121
Antoine Pitrou98b46702010-09-18 22:59:00 +00004122 # Non-blocking ops
Antoine Pitrou834bd812010-10-13 16:17:14 +00004123 # NOTE: to set `read_file` as non-blocking, we must call
Antoine Pitrou98b46702010-09-18 22:59:00 +00004124 # `cli_conn.setblocking` and vice-versa (see setUp / clientSetUp).
4125
4126 def testSmallReadNonBlocking(self):
4127 self.cli_conn.setblocking(False)
Antoine Pitrou834bd812010-10-13 16:17:14 +00004128 self.assertEqual(self.read_file.readinto(bytearray(10)), None)
4129 self.assertEqual(self.read_file.read(len(self.read_msg) - 3), None)
Antoine Pitrou98b46702010-09-18 22:59:00 +00004130 self.evt1.set()
4131 self.evt2.wait(1.0)
Antoine Pitrou834bd812010-10-13 16:17:14 +00004132 first_seg = self.read_file.read(len(self.read_msg) - 3)
Antoine Pitrou43bf0452011-04-04 01:21:37 +02004133 if first_seg is None:
4134 # Data not arrived (can happen under Windows), wait a bit
4135 time.sleep(0.5)
4136 first_seg = self.read_file.read(len(self.read_msg) - 3)
Antoine Pitrou98b46702010-09-18 22:59:00 +00004137 buf = bytearray(10)
Antoine Pitrou834bd812010-10-13 16:17:14 +00004138 n = self.read_file.readinto(buf)
Antoine Pitrou98b46702010-09-18 22:59:00 +00004139 self.assertEqual(n, 3)
4140 msg = first_seg + buf[:n]
Antoine Pitrou834bd812010-10-13 16:17:14 +00004141 self.assertEqual(msg, self.read_msg)
4142 self.assertEqual(self.read_file.readinto(bytearray(16)), None)
4143 self.assertEqual(self.read_file.read(1), None)
Antoine Pitrou98b46702010-09-18 22:59:00 +00004144
4145 def _testSmallReadNonBlocking(self):
4146 self.evt1.wait(1.0)
Antoine Pitrou834bd812010-10-13 16:17:14 +00004147 self.write_file.write(self.write_msg)
4148 self.write_file.flush()
Antoine Pitrou98b46702010-09-18 22:59:00 +00004149 self.evt2.set()
4150 # Avoid cloding the socket before the server test has finished,
4151 # otherwise system recv() will return 0 instead of EWOULDBLOCK.
4152 self.serv_finished.wait(5.0)
4153
4154 def testWriteNonBlocking(self):
4155 self.cli_finished.wait(5.0)
4156 # The client thread can't skip directly - the SkipTest exception
4157 # would appear as a failure.
4158 if self.serv_skipped:
4159 self.skipTest(self.serv_skipped)
4160
4161 def _testWriteNonBlocking(self):
4162 self.serv_skipped = None
4163 self.serv_conn.setblocking(False)
4164 # Try to saturate the socket buffer pipe with repeated large writes.
Charles-François Natali5fd26422013-08-29 19:01:40 +02004165 BIG = b"x" * support.SOCK_MAX_SIZE
Antoine Pitrou98b46702010-09-18 22:59:00 +00004166 LIMIT = 10
4167 # The first write() succeeds since a chunk of data can be buffered
Antoine Pitrou834bd812010-10-13 16:17:14 +00004168 n = self.write_file.write(BIG)
Antoine Pitrou98b46702010-09-18 22:59:00 +00004169 self.assertGreater(n, 0)
4170 for i in range(LIMIT):
Antoine Pitrou834bd812010-10-13 16:17:14 +00004171 n = self.write_file.write(BIG)
Antoine Pitrou98b46702010-09-18 22:59:00 +00004172 if n is None:
4173 # Succeeded
4174 break
4175 self.assertGreater(n, 0)
4176 else:
4177 # Let us know that this test didn't manage to establish
4178 # the expected conditions. This is not a failure in itself but,
4179 # if it happens repeatedly, the test should be fixed.
4180 self.serv_skipped = "failed to saturate the socket buffer"
4181
Gregory P. Smithde3369f2009-01-12 04:50:11 +00004182
Guido van Rossum8c943832002-08-08 01:00:28 +00004183class LineBufferedFileObjectClassTestCase(FileObjectClassTestCase):
4184
4185 bufsize = 1 # Default-buffered for reading; line-buffered for writing
4186
4187
4188class SmallBufferedFileObjectClassTestCase(FileObjectClassTestCase):
4189
4190 bufsize = 2 # Exercise the buffering code
Guido van Rossume9f66142002-08-07 15:46:19 +00004191
Thomas Woutersb2137042007-02-01 18:02:27 +00004192
Antoine Pitrou834bd812010-10-13 16:17:14 +00004193class UnicodeReadFileObjectClassTestCase(FileObjectClassTestCase):
4194 """Tests for socket.makefile() in text mode (rather than binary)"""
4195
4196 read_mode = 'r'
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00004197 read_msg = MSG.decode('utf-8')
Antoine Pitrou834bd812010-10-13 16:17:14 +00004198 write_mode = 'wb'
4199 write_msg = MSG
4200 newline = ''
4201
4202
4203class UnicodeWriteFileObjectClassTestCase(FileObjectClassTestCase):
4204 """Tests for socket.makefile() in text mode (rather than binary)"""
4205
4206 read_mode = 'rb'
4207 read_msg = MSG
4208 write_mode = 'w'
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00004209 write_msg = MSG.decode('utf-8')
Antoine Pitrou834bd812010-10-13 16:17:14 +00004210 newline = ''
4211
4212
4213class UnicodeReadWriteFileObjectClassTestCase(FileObjectClassTestCase):
4214 """Tests for socket.makefile() in text mode (rather than binary)"""
4215
4216 read_mode = 'r'
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00004217 read_msg = MSG.decode('utf-8')
Antoine Pitrou834bd812010-10-13 16:17:14 +00004218 write_mode = 'w'
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00004219 write_msg = MSG.decode('utf-8')
Antoine Pitrou834bd812010-10-13 16:17:14 +00004220 newline = ''
4221
4222
Guido van Rossumd8faa362007-04-27 19:54:29 +00004223class NetworkConnectionTest(object):
4224 """Prove network connection."""
Guido van Rossum7d0a8262007-05-21 23:13:11 +00004225
Guido van Rossumd8faa362007-04-27 19:54:29 +00004226 def clientSetUp(self):
Christian Heimes5e696852008-04-09 08:37:03 +00004227 # We're inherited below by BasicTCPTest2, which also inherits
4228 # BasicTCPTest, which defines self.port referenced below.
4229 self.cli = socket.create_connection((HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +00004230 self.serv_conn = self.cli
4231
4232class BasicTCPTest2(NetworkConnectionTest, BasicTCPTest):
4233 """Tests that NetworkConnection does not break existing TCP functionality.
4234 """
4235
4236class NetworkConnectionNoServer(unittest.TestCase):
Guido van Rossum7d0a8262007-05-21 23:13:11 +00004237
Antoine Pitrou4b92b5f2010-09-07 21:05:49 +00004238 class MockSocket(socket.socket):
4239 def connect(self, *args):
4240 raise socket.timeout('timed out')
4241
4242 @contextlib.contextmanager
4243 def mocked_socket_module(self):
4244 """Return a socket which times out on connect"""
4245 old_socket = socket.socket
4246 socket.socket = self.MockSocket
4247 try:
4248 yield
4249 finally:
4250 socket.socket = old_socket
4251
4252 def test_connect(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00004253 port = support.find_unused_port()
Antoine Pitrou4b92b5f2010-09-07 21:05:49 +00004254 cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Brian Curtin21ebbb72010-11-02 02:07:09 +00004255 self.addCleanup(cli.close)
Andrew Svetlov0832af62012-12-18 23:10:48 +02004256 with self.assertRaises(OSError) as cm:
Antoine Pitrou4b92b5f2010-09-07 21:05:49 +00004257 cli.connect((HOST, port))
4258 self.assertEqual(cm.exception.errno, errno.ECONNREFUSED)
4259
4260 def test_create_connection(self):
4261 # Issue #9792: errors raised by create_connection() should have
4262 # a proper errno attribute.
4263 port = support.find_unused_port()
Andrew Svetlov0832af62012-12-18 23:10:48 +02004264 with self.assertRaises(OSError) as cm:
Antoine Pitrou4b92b5f2010-09-07 21:05:49 +00004265 socket.create_connection((HOST, port))
Trent Nelson45bb6132012-10-17 06:15:15 -04004266
4267 # Issue #16257: create_connection() calls getaddrinfo() against
4268 # 'localhost'. This may result in an IPV6 addr being returned
4269 # as well as an IPV4 one:
4270 # >>> socket.getaddrinfo('localhost', port, 0, SOCK_STREAM)
4271 # >>> [(2, 2, 0, '', ('127.0.0.1', 41230)),
4272 # (26, 2, 0, '', ('::1', 41230, 0, 0))]
4273 #
4274 # create_connection() enumerates through all the addresses returned
4275 # and if it doesn't successfully bind to any of them, it propagates
4276 # the last exception it encountered.
4277 #
4278 # On Solaris, ENETUNREACH is returned in this circumstance instead
4279 # of ECONNREFUSED. So, if that errno exists, add it to our list of
4280 # expected errnos.
4281 expected_errnos = [ errno.ECONNREFUSED, ]
4282 if hasattr(errno, 'ENETUNREACH'):
4283 expected_errnos.append(errno.ENETUNREACH)
4284
4285 self.assertIn(cm.exception.errno, expected_errnos)
Antoine Pitrou4b92b5f2010-09-07 21:05:49 +00004286
4287 def test_create_connection_timeout(self):
4288 # Issue #9792: create_connection() should not recast timeout errors
4289 # as generic socket errors.
4290 with self.mocked_socket_module():
4291 with self.assertRaises(socket.timeout):
4292 socket.create_connection((HOST, 1234))
4293
Guido van Rossumd8faa362007-04-27 19:54:29 +00004294
Victor Stinner45df8202010-04-28 22:31:17 +00004295@unittest.skipUnless(thread, 'Threading required for this test.')
Guido van Rossumd8faa362007-04-27 19:54:29 +00004296class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest):
4297
4298 def __init__(self, methodName='runTest'):
4299 SocketTCPTest.__init__(self, methodName=methodName)
4300 ThreadableTest.__init__(self)
4301
4302 def clientSetUp(self):
Gregory P. Smithb4066372010-01-03 03:28:29 +00004303 self.source_port = support.find_unused_port()
Guido van Rossumd8faa362007-04-27 19:54:29 +00004304
4305 def clientTearDown(self):
4306 self.cli.close()
4307 self.cli = None
4308 ThreadableTest.clientTearDown(self)
4309
4310 def _justAccept(self):
4311 conn, addr = self.serv.accept()
Brian Curtin21ebbb72010-11-02 02:07:09 +00004312 conn.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00004313
4314 testFamily = _justAccept
4315 def _testFamily(self):
Christian Heimes5e696852008-04-09 08:37:03 +00004316 self.cli = socket.create_connection((HOST, self.port), timeout=30)
Brian Curtin21ebbb72010-11-02 02:07:09 +00004317 self.addCleanup(self.cli.close)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004318 self.assertEqual(self.cli.family, 2)
4319
Gregory P. Smitha81d8812010-01-03 15:09:32 +00004320 testSourceAddress = _justAccept
4321 def _testSourceAddress(self):
Gregory P. Smithb4066372010-01-03 03:28:29 +00004322 self.cli = socket.create_connection((HOST, self.port), timeout=30,
4323 source_address=('', self.source_port))
Brian Curtin21ebbb72010-11-02 02:07:09 +00004324 self.addCleanup(self.cli.close)
Gregory P. Smithb4066372010-01-03 03:28:29 +00004325 self.assertEqual(self.cli.getsockname()[1], self.source_port)
Gregory P. Smitha81d8812010-01-03 15:09:32 +00004326 # The port number being used is sufficient to show that the bind()
4327 # call happened.
Gregory P. Smithb4066372010-01-03 03:28:29 +00004328
Guido van Rossumd8faa362007-04-27 19:54:29 +00004329 testTimeoutDefault = _justAccept
4330 def _testTimeoutDefault(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +00004331 # passing no explicit timeout uses socket's global default
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00004332 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +00004333 socket.setdefaulttimeout(42)
4334 try:
4335 self.cli = socket.create_connection((HOST, self.port))
Brian Curtin21ebbb72010-11-02 02:07:09 +00004336 self.addCleanup(self.cli.close)
Georg Brandlf78e02b2008-06-10 17:40:04 +00004337 finally:
4338 socket.setdefaulttimeout(None)
Ezio Melottib3aedd42010-11-20 19:04:17 +00004339 self.assertEqual(self.cli.gettimeout(), 42)
Georg Brandlf78e02b2008-06-10 17:40:04 +00004340
4341 testTimeoutNone = _justAccept
4342 def _testTimeoutNone(self):
4343 # None timeout means the same as sock.settimeout(None)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00004344 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +00004345 socket.setdefaulttimeout(30)
4346 try:
4347 self.cli = socket.create_connection((HOST, self.port), timeout=None)
Brian Curtin21ebbb72010-11-02 02:07:09 +00004348 self.addCleanup(self.cli.close)
Georg Brandlf78e02b2008-06-10 17:40:04 +00004349 finally:
4350 socket.setdefaulttimeout(None)
4351 self.assertEqual(self.cli.gettimeout(), None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004352
4353 testTimeoutValueNamed = _justAccept
4354 def _testTimeoutValueNamed(self):
Christian Heimes5e696852008-04-09 08:37:03 +00004355 self.cli = socket.create_connection((HOST, self.port), timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004356 self.assertEqual(self.cli.gettimeout(), 30)
4357
4358 testTimeoutValueNonamed = _justAccept
4359 def _testTimeoutValueNonamed(self):
Christian Heimes5e696852008-04-09 08:37:03 +00004360 self.cli = socket.create_connection((HOST, self.port), 30)
Brian Curtin21ebbb72010-11-02 02:07:09 +00004361 self.addCleanup(self.cli.close)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004362 self.assertEqual(self.cli.gettimeout(), 30)
4363
Victor Stinner45df8202010-04-28 22:31:17 +00004364@unittest.skipUnless(thread, 'Threading required for this test.')
Guido van Rossumd8faa362007-04-27 19:54:29 +00004365class NetworkConnectionBehaviourTest(SocketTCPTest, ThreadableTest):
4366
4367 def __init__(self, methodName='runTest'):
4368 SocketTCPTest.__init__(self, methodName=methodName)
4369 ThreadableTest.__init__(self)
4370
4371 def clientSetUp(self):
4372 pass
4373
4374 def clientTearDown(self):
4375 self.cli.close()
4376 self.cli = None
4377 ThreadableTest.clientTearDown(self)
4378
4379 def testInsideTimeout(self):
4380 conn, addr = self.serv.accept()
Brian Curtin21ebbb72010-11-02 02:07:09 +00004381 self.addCleanup(conn.close)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004382 time.sleep(3)
Guido van Rossum7d0a8262007-05-21 23:13:11 +00004383 conn.send(b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +00004384 testOutsideTimeout = testInsideTimeout
4385
4386 def _testInsideTimeout(self):
Christian Heimes5e696852008-04-09 08:37:03 +00004387 self.cli = sock = socket.create_connection((HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +00004388 data = sock.recv(5)
Guido van Rossum7d0a8262007-05-21 23:13:11 +00004389 self.assertEqual(data, b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +00004390
4391 def _testOutsideTimeout(self):
Christian Heimes5e696852008-04-09 08:37:03 +00004392 self.cli = sock = socket.create_connection((HOST, self.port), timeout=1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00004393 self.assertRaises(socket.timeout, lambda: sock.recv(5))
Guido van Rossumd8faa362007-04-27 19:54:29 +00004394
4395
Raymond Hettinger11a35f52003-06-29 04:40:22 +00004396class TCPTimeoutTest(SocketTCPTest):
4397
4398 def testTCPTimeout(self):
4399 def raise_timeout(*args, **kwargs):
4400 self.serv.settimeout(1.0)
4401 self.serv.accept()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00004402 self.assertRaises(socket.timeout, raise_timeout,
Raymond Hettinger11a35f52003-06-29 04:40:22 +00004403 "Error generating a timeout exception (TCP)")
4404
4405 def testTimeoutZero(self):
4406 ok = False
4407 try:
4408 self.serv.settimeout(0.0)
4409 foo = self.serv.accept()
4410 except socket.timeout:
4411 self.fail("caught timeout instead of error (TCP)")
Andrew Svetlov0832af62012-12-18 23:10:48 +02004412 except OSError:
Raymond Hettinger11a35f52003-06-29 04:40:22 +00004413 ok = True
4414 except:
4415 self.fail("caught unexpected exception (TCP)")
4416 if not ok:
4417 self.fail("accept() returned success when we did not expect it")
4418
Serhiy Storchaka43767632013-11-03 21:31:38 +02004419 @unittest.skipUnless(hasattr(signal, 'alarm'),
4420 'test needs signal.alarm()')
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004421 def testInterruptedTimeout(self):
4422 # XXX I don't know how to do this test on MSWindows or any other
4423 # plaform that doesn't support signal.alarm() or os.kill(), though
4424 # the bug should have existed on all platforms.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004425 self.serv.settimeout(5.0) # must be longer than alarm
4426 class Alarm(Exception):
4427 pass
4428 def alarm_handler(signal, frame):
4429 raise Alarm
4430 old_alarm = signal.signal(signal.SIGALRM, alarm_handler)
4431 try:
4432 signal.alarm(2) # POSIX allows alarm to be up to 1 second early
4433 try:
4434 foo = self.serv.accept()
4435 except socket.timeout:
4436 self.fail("caught timeout instead of Alarm")
4437 except Alarm:
4438 pass
4439 except:
Christian Heimesbbe741d2008-03-28 10:53:29 +00004440 self.fail("caught other exception instead of Alarm:"
4441 " %s(%s):\n%s" %
4442 (sys.exc_info()[:2] + (traceback.format_exc(),)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004443 else:
4444 self.fail("nothing caught")
Christian Heimesbbe741d2008-03-28 10:53:29 +00004445 finally:
4446 signal.alarm(0) # shut off alarm
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004447 except Alarm:
4448 self.fail("got Alarm in wrong place")
4449 finally:
4450 # no alarm can be pending. Safe to restore old handler.
4451 signal.signal(signal.SIGALRM, old_alarm)
4452
Ezio Melotti7f78ddc2011-11-18 18:33:14 +02004453class UDPTimeoutTest(SocketUDPTest):
Raymond Hettinger11a35f52003-06-29 04:40:22 +00004454
4455 def testUDPTimeout(self):
4456 def raise_timeout(*args, **kwargs):
4457 self.serv.settimeout(1.0)
4458 self.serv.recv(1024)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00004459 self.assertRaises(socket.timeout, raise_timeout,
Raymond Hettinger11a35f52003-06-29 04:40:22 +00004460 "Error generating a timeout exception (UDP)")
4461
4462 def testTimeoutZero(self):
4463 ok = False
4464 try:
4465 self.serv.settimeout(0.0)
4466 foo = self.serv.recv(1024)
4467 except socket.timeout:
4468 self.fail("caught timeout instead of error (UDP)")
Andrew Svetlov0832af62012-12-18 23:10:48 +02004469 except OSError:
Raymond Hettinger11a35f52003-06-29 04:40:22 +00004470 ok = True
4471 except:
4472 self.fail("caught unexpected exception (UDP)")
4473 if not ok:
4474 self.fail("recv() returned success when we did not expect it")
4475
4476class TestExceptions(unittest.TestCase):
4477
4478 def testExceptionTree(self):
Andrew Svetlov0832af62012-12-18 23:10:48 +02004479 self.assertTrue(issubclass(OSError, Exception))
4480 self.assertTrue(issubclass(socket.herror, OSError))
4481 self.assertTrue(issubclass(socket.gaierror, OSError))
4482 self.assertTrue(issubclass(socket.timeout, OSError))
Raymond Hettinger11a35f52003-06-29 04:40:22 +00004483
Serhiy Storchaka43767632013-11-03 21:31:38 +02004484@unittest.skipUnless(sys.platform == 'linux', 'Linux specific test')
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004485class TestLinuxAbstractNamespace(unittest.TestCase):
4486
4487 UNIX_PATH_MAX = 108
4488
4489 def testLinuxAbstractNamespace(self):
Charles-François Natalib10c71d2013-05-21 10:45:46 +02004490 address = b"\x00python-test-hello\x00\xff"
Victor Stinner1d5eb342011-01-03 14:30:46 +00004491 with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s1:
4492 s1.bind(address)
Charles-François Natali6e204602014-07-23 19:28:13 +01004493 s1.listen()
Victor Stinner1d5eb342011-01-03 14:30:46 +00004494 with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s2:
4495 s2.connect(s1.getsockname())
4496 with s1.accept()[0] as s3:
4497 self.assertEqual(s1.getsockname(), address)
4498 self.assertEqual(s2.getpeername(), address)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004499
4500 def testMaxName(self):
Charles-François Natalib10c71d2013-05-21 10:45:46 +02004501 address = b"\x00" + b"h" * (self.UNIX_PATH_MAX - 1)
Victor Stinner1d5eb342011-01-03 14:30:46 +00004502 with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
4503 s.bind(address)
4504 self.assertEqual(s.getsockname(), address)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004505
4506 def testNameOverflow(self):
4507 address = "\x00" + "h" * self.UNIX_PATH_MAX
Victor Stinner1d5eb342011-01-03 14:30:46 +00004508 with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
Andrew Svetlov0832af62012-12-18 23:10:48 +02004509 self.assertRaises(OSError, s.bind, address)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004510
Charles-François Natalib10c71d2013-05-21 10:45:46 +02004511 def testStrName(self):
4512 # Check that an abstract name can be passed as a string.
Antoine Pitrou6ec29e22011-12-16 14:46:36 +01004513 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
4514 try:
Charles-François Natalib10c71d2013-05-21 10:45:46 +02004515 s.bind("\x00python\x00test\x00")
4516 self.assertEqual(s.getsockname(), b"\x00python\x00test\x00")
Antoine Pitrou6ec29e22011-12-16 14:46:36 +01004517 finally:
4518 s.close()
4519
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004520 def testBytearrayName(self):
4521 # Check that an abstract name can be passed as a bytearray.
4522 with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
4523 s.bind(bytearray(b"\x00python\x00test\x00"))
4524 self.assertEqual(s.getsockname(), b"\x00python\x00test\x00")
4525
Serhiy Storchaka43767632013-11-03 21:31:38 +02004526@unittest.skipUnless(hasattr(socket, 'AF_UNIX'), 'test needs socket.AF_UNIX')
Antoine Pitrou6ec29e22011-12-16 14:46:36 +01004527class TestUnixDomain(unittest.TestCase):
4528
4529 def setUp(self):
4530 self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
4531
4532 def tearDown(self):
4533 self.sock.close()
4534
4535 def encoded(self, path):
4536 # Return the given path encoded in the file system encoding,
4537 # or skip the test if this is not possible.
4538 try:
4539 return os.fsencode(path)
4540 except UnicodeEncodeError:
4541 self.skipTest(
4542 "Pathname {0!a} cannot be represented in file "
4543 "system encoding {1!r}".format(
4544 path, sys.getfilesystemencoding()))
4545
Antoine Pitrou16374872011-12-16 15:04:12 +01004546 def bind(self, sock, path):
4547 # Bind the socket
4548 try:
4549 sock.bind(path)
4550 except OSError as e:
4551 if str(e) == "AF_UNIX path too long":
4552 self.skipTest(
Serhiy Storchakad65c9492015-11-02 14:10:23 +02004553 "Pathname {0!a} is too long to serve as an AF_UNIX path"
Antoine Pitrou16374872011-12-16 15:04:12 +01004554 .format(path))
4555 else:
4556 raise
4557
Antoine Pitrou6ec29e22011-12-16 14:46:36 +01004558 def testStrAddr(self):
4559 # Test binding to and retrieving a normal string pathname.
4560 path = os.path.abspath(support.TESTFN)
Antoine Pitrou16374872011-12-16 15:04:12 +01004561 self.bind(self.sock, path)
Antoine Pitrou6ec29e22011-12-16 14:46:36 +01004562 self.addCleanup(support.unlink, path)
4563 self.assertEqual(self.sock.getsockname(), path)
4564
4565 def testBytesAddr(self):
4566 # Test binding to a bytes pathname.
4567 path = os.path.abspath(support.TESTFN)
Antoine Pitrou16374872011-12-16 15:04:12 +01004568 self.bind(self.sock, self.encoded(path))
Antoine Pitrou6ec29e22011-12-16 14:46:36 +01004569 self.addCleanup(support.unlink, path)
4570 self.assertEqual(self.sock.getsockname(), path)
4571
4572 def testSurrogateescapeBind(self):
4573 # Test binding to a valid non-ASCII pathname, with the
4574 # non-ASCII bytes supplied using surrogateescape encoding.
4575 path = os.path.abspath(support.TESTFN_UNICODE)
4576 b = self.encoded(path)
Antoine Pitrou16374872011-12-16 15:04:12 +01004577 self.bind(self.sock, b.decode("ascii", "surrogateescape"))
Antoine Pitrou6ec29e22011-12-16 14:46:36 +01004578 self.addCleanup(support.unlink, path)
4579 self.assertEqual(self.sock.getsockname(), path)
4580
4581 def testUnencodableAddr(self):
4582 # Test binding to a pathname that cannot be encoded in the
4583 # file system encoding.
4584 if support.TESTFN_UNENCODABLE is None:
4585 self.skipTest("No unencodable filename available")
4586 path = os.path.abspath(support.TESTFN_UNENCODABLE)
Antoine Pitrou16374872011-12-16 15:04:12 +01004587 self.bind(self.sock, path)
Antoine Pitrou6ec29e22011-12-16 14:46:36 +01004588 self.addCleanup(support.unlink, path)
4589 self.assertEqual(self.sock.getsockname(), path)
Raymond Hettinger11a35f52003-06-29 04:40:22 +00004590
Victor Stinner45df8202010-04-28 22:31:17 +00004591@unittest.skipUnless(thread, 'Threading required for this test.')
Thomas Wouters477c8d52006-05-27 19:21:47 +00004592class BufferIOTest(SocketConnectedTest):
4593 """
4594 Test the buffer versions of socket.recv() and socket.send().
4595 """
4596 def __init__(self, methodName='runTest'):
4597 SocketConnectedTest.__init__(self, methodName=methodName)
4598
Antoine Pitrou25480782010-03-17 22:50:28 +00004599 def testRecvIntoArray(self):
Antoine Pitrou2f89aa62008-08-02 21:02:48 +00004600 buf = bytearray(1024)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00004601 nbytes = self.cli_conn.recv_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00004602 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00004603 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00004604 self.assertEqual(msg, MSG)
4605
Antoine Pitrou25480782010-03-17 22:50:28 +00004606 def _testRecvIntoArray(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00004607 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00004608 self.serv_conn.send(buf)
4609
Antoine Pitrou25480782010-03-17 22:50:28 +00004610 def testRecvIntoBytearray(self):
4611 buf = bytearray(1024)
4612 nbytes = self.cli_conn.recv_into(buf)
4613 self.assertEqual(nbytes, len(MSG))
4614 msg = buf[:len(MSG)]
4615 self.assertEqual(msg, MSG)
4616
4617 _testRecvIntoBytearray = _testRecvIntoArray
4618
4619 def testRecvIntoMemoryview(self):
4620 buf = bytearray(1024)
4621 nbytes = self.cli_conn.recv_into(memoryview(buf))
4622 self.assertEqual(nbytes, len(MSG))
4623 msg = buf[:len(MSG)]
4624 self.assertEqual(msg, MSG)
4625
4626 _testRecvIntoMemoryview = _testRecvIntoArray
4627
4628 def testRecvFromIntoArray(self):
Antoine Pitrou2f89aa62008-08-02 21:02:48 +00004629 buf = bytearray(1024)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00004630 nbytes, addr = self.cli_conn.recvfrom_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00004631 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00004632 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00004633 self.assertEqual(msg, MSG)
4634
Antoine Pitrou25480782010-03-17 22:50:28 +00004635 def _testRecvFromIntoArray(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00004636 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00004637 self.serv_conn.send(buf)
4638
Antoine Pitrou25480782010-03-17 22:50:28 +00004639 def testRecvFromIntoBytearray(self):
4640 buf = bytearray(1024)
4641 nbytes, addr = self.cli_conn.recvfrom_into(buf)
4642 self.assertEqual(nbytes, len(MSG))
4643 msg = buf[:len(MSG)]
4644 self.assertEqual(msg, MSG)
4645
4646 _testRecvFromIntoBytearray = _testRecvFromIntoArray
4647
4648 def testRecvFromIntoMemoryview(self):
4649 buf = bytearray(1024)
4650 nbytes, addr = self.cli_conn.recvfrom_into(memoryview(buf))
4651 self.assertEqual(nbytes, len(MSG))
4652 msg = buf[:len(MSG)]
4653 self.assertEqual(msg, MSG)
4654
4655 _testRecvFromIntoMemoryview = _testRecvFromIntoArray
4656
Benjamin Petersonc6b37e22014-01-13 23:14:42 -05004657 def testRecvFromIntoSmallBuffer(self):
4658 # See issue #20246.
4659 buf = bytearray(8)
4660 self.assertRaises(ValueError, self.cli_conn.recvfrom_into, buf, 1024)
4661
4662 def _testRecvFromIntoSmallBuffer(self):
Stefan Krah6b2e5592014-01-21 22:58:40 +01004663 self.serv_conn.send(MSG)
Benjamin Petersonc6b37e22014-01-13 23:14:42 -05004664
Benjamin Petersonbd1d12e2014-01-14 00:27:42 -05004665 def testRecvFromIntoEmptyBuffer(self):
4666 buf = bytearray()
4667 self.cli_conn.recvfrom_into(buf)
4668 self.cli_conn.recvfrom_into(buf, 0)
4669
4670 _testRecvFromIntoEmptyBuffer = _testRecvFromIntoArray
4671
Christian Heimes043d6f62008-01-07 17:19:16 +00004672
4673TIPC_STYPE = 2000
4674TIPC_LOWER = 200
4675TIPC_UPPER = 210
4676
4677def isTipcAvailable():
4678 """Check if the TIPC module is loaded
4679
4680 The TIPC module is not loaded automatically on Ubuntu and probably
4681 other Linux distros.
4682 """
4683 if not hasattr(socket, "AF_TIPC"):
4684 return False
4685 if not os.path.isfile("/proc/modules"):
4686 return False
4687 with open("/proc/modules") as f:
4688 for line in f:
4689 if line.startswith("tipc "):
4690 return True
Christian Heimes043d6f62008-01-07 17:19:16 +00004691 return False
4692
Serhiy Storchaka43767632013-11-03 21:31:38 +02004693@unittest.skipUnless(isTipcAvailable(),
4694 "TIPC module is not loaded, please 'sudo modprobe tipc'")
Antoine Pitrou86aed0b2011-10-02 23:33:19 +02004695class TIPCTest(unittest.TestCase):
Christian Heimes043d6f62008-01-07 17:19:16 +00004696 def testRDM(self):
4697 srv = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
4698 cli = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
Antoine Pitrou86aed0b2011-10-02 23:33:19 +02004699 self.addCleanup(srv.close)
4700 self.addCleanup(cli.close)
Christian Heimes043d6f62008-01-07 17:19:16 +00004701
4702 srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
4703 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
4704 TIPC_LOWER, TIPC_UPPER)
4705 srv.bind(srvaddr)
4706
4707 sendaddr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
4708 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
4709 cli.sendto(MSG, sendaddr)
4710
4711 msg, recvaddr = srv.recvfrom(1024)
4712
4713 self.assertEqual(cli.getsockname(), recvaddr)
4714 self.assertEqual(msg, MSG)
4715
4716
Serhiy Storchaka43767632013-11-03 21:31:38 +02004717@unittest.skipUnless(isTipcAvailable(),
4718 "TIPC module is not loaded, please 'sudo modprobe tipc'")
Antoine Pitrou86aed0b2011-10-02 23:33:19 +02004719class TIPCThreadableTest(unittest.TestCase, ThreadableTest):
Christian Heimes043d6f62008-01-07 17:19:16 +00004720 def __init__(self, methodName = 'runTest'):
4721 unittest.TestCase.__init__(self, methodName = methodName)
4722 ThreadableTest.__init__(self)
4723
4724 def setUp(self):
4725 self.srv = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
Antoine Pitrou86aed0b2011-10-02 23:33:19 +02004726 self.addCleanup(self.srv.close)
Christian Heimes043d6f62008-01-07 17:19:16 +00004727 self.srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
4728 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
4729 TIPC_LOWER, TIPC_UPPER)
4730 self.srv.bind(srvaddr)
Charles-François Natali6e204602014-07-23 19:28:13 +01004731 self.srv.listen()
Christian Heimes043d6f62008-01-07 17:19:16 +00004732 self.serverExplicitReady()
4733 self.conn, self.connaddr = self.srv.accept()
Antoine Pitrou86aed0b2011-10-02 23:33:19 +02004734 self.addCleanup(self.conn.close)
Christian Heimes043d6f62008-01-07 17:19:16 +00004735
4736 def clientSetUp(self):
4737 # The is a hittable race between serverExplicitReady() and the
4738 # accept() call; sleep a little while to avoid it, otherwise
4739 # we could get an exception
4740 time.sleep(0.1)
4741 self.cli = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
Antoine Pitrou86aed0b2011-10-02 23:33:19 +02004742 self.addCleanup(self.cli.close)
Christian Heimes043d6f62008-01-07 17:19:16 +00004743 addr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
4744 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
4745 self.cli.connect(addr)
4746 self.cliaddr = self.cli.getsockname()
4747
4748 def testStream(self):
4749 msg = self.conn.recv(1024)
4750 self.assertEqual(msg, MSG)
4751 self.assertEqual(self.cliaddr, self.connaddr)
4752
4753 def _testStream(self):
4754 self.cli.send(MSG)
4755 self.cli.close()
4756
4757
Giampaolo Rodolàb383dbb2010-09-08 22:44:12 +00004758@unittest.skipUnless(thread, 'Threading required for this test.')
4759class ContextManagersTest(ThreadedTCPSocketTest):
4760
4761 def _testSocketClass(self):
4762 # base test
4763 with socket.socket() as sock:
4764 self.assertFalse(sock._closed)
4765 self.assertTrue(sock._closed)
4766 # close inside with block
4767 with socket.socket() as sock:
4768 sock.close()
4769 self.assertTrue(sock._closed)
4770 # exception inside with block
4771 with socket.socket() as sock:
Andrew Svetlov0832af62012-12-18 23:10:48 +02004772 self.assertRaises(OSError, sock.sendall, b'foo')
Giampaolo Rodolàb383dbb2010-09-08 22:44:12 +00004773 self.assertTrue(sock._closed)
4774
4775 def testCreateConnectionBase(self):
4776 conn, addr = self.serv.accept()
Brian Curtin21ebbb72010-11-02 02:07:09 +00004777 self.addCleanup(conn.close)
Giampaolo Rodolàb383dbb2010-09-08 22:44:12 +00004778 data = conn.recv(1024)
4779 conn.sendall(data)
4780
4781 def _testCreateConnectionBase(self):
4782 address = self.serv.getsockname()
4783 with socket.create_connection(address) as sock:
4784 self.assertFalse(sock._closed)
4785 sock.sendall(b'foo')
4786 self.assertEqual(sock.recv(1024), b'foo')
4787 self.assertTrue(sock._closed)
4788
4789 def testCreateConnectionClose(self):
4790 conn, addr = self.serv.accept()
Brian Curtin21ebbb72010-11-02 02:07:09 +00004791 self.addCleanup(conn.close)
Giampaolo Rodolàb383dbb2010-09-08 22:44:12 +00004792 data = conn.recv(1024)
4793 conn.sendall(data)
4794
4795 def _testCreateConnectionClose(self):
4796 address = self.serv.getsockname()
4797 with socket.create_connection(address) as sock:
4798 sock.close()
4799 self.assertTrue(sock._closed)
Andrew Svetlov0832af62012-12-18 23:10:48 +02004800 self.assertRaises(OSError, sock.sendall, b'foo')
Giampaolo Rodolàb383dbb2010-09-08 22:44:12 +00004801
Antoine Pitrouacd0fda2010-10-23 17:01:44 +00004802
Victor Stinnerdaf45552013-08-28 00:53:59 +02004803class InheritanceTest(unittest.TestCase):
4804 @unittest.skipUnless(hasattr(socket, "SOCK_CLOEXEC"),
4805 "SOCK_CLOEXEC not defined")
Charles-François Natali239bb962011-06-03 12:55:15 +02004806 @support.requires_linux_version(2, 6, 28)
Antoine Pitroub1c54962010-10-14 15:05:38 +00004807 def test_SOCK_CLOEXEC(self):
Victor Stinner1d5eb342011-01-03 14:30:46 +00004808 with socket.socket(socket.AF_INET,
4809 socket.SOCK_STREAM | socket.SOCK_CLOEXEC) as s:
4810 self.assertTrue(s.type & socket.SOCK_CLOEXEC)
Victor Stinnerd39dca92013-08-28 12:28:18 +02004811 self.assertFalse(s.get_inheritable())
Victor Stinnerdaf45552013-08-28 00:53:59 +02004812
4813 def test_default_inheritable(self):
4814 sock = socket.socket()
4815 with sock:
4816 self.assertEqual(sock.get_inheritable(), False)
4817
4818 def test_dup(self):
4819 sock = socket.socket()
4820 with sock:
4821 newsock = sock.dup()
4822 sock.close()
4823 with newsock:
4824 self.assertEqual(newsock.get_inheritable(), False)
4825
4826 def test_set_inheritable(self):
4827 sock = socket.socket()
4828 with sock:
4829 sock.set_inheritable(True)
4830 self.assertEqual(sock.get_inheritable(), True)
4831
4832 sock.set_inheritable(False)
4833 self.assertEqual(sock.get_inheritable(), False)
4834
Victor Stinner4f7a36f2013-09-08 14:14:38 +02004835 @unittest.skipIf(fcntl is None, "need fcntl")
4836 def test_get_inheritable_cloexec(self):
4837 sock = socket.socket()
4838 with sock:
4839 fd = sock.fileno()
4840 self.assertEqual(sock.get_inheritable(), False)
Victor Stinnera3c18d02013-09-08 11:53:09 +02004841
Victor Stinner4f7a36f2013-09-08 14:14:38 +02004842 # clear FD_CLOEXEC flag
4843 flags = fcntl.fcntl(fd, fcntl.F_GETFD)
4844 flags &= ~fcntl.FD_CLOEXEC
4845 fcntl.fcntl(fd, fcntl.F_SETFD, flags)
Victor Stinnera3c18d02013-09-08 11:53:09 +02004846
Victor Stinner4f7a36f2013-09-08 14:14:38 +02004847 self.assertEqual(sock.get_inheritable(), True)
Victor Stinnera3c18d02013-09-08 11:53:09 +02004848
Victor Stinner4f7a36f2013-09-08 14:14:38 +02004849 @unittest.skipIf(fcntl is None, "need fcntl")
4850 def test_set_inheritable_cloexec(self):
4851 sock = socket.socket()
4852 with sock:
4853 fd = sock.fileno()
4854 self.assertEqual(fcntl.fcntl(fd, fcntl.F_GETFD) & fcntl.FD_CLOEXEC,
4855 fcntl.FD_CLOEXEC)
Victor Stinnera3c18d02013-09-08 11:53:09 +02004856
Victor Stinner4f7a36f2013-09-08 14:14:38 +02004857 sock.set_inheritable(True)
4858 self.assertEqual(fcntl.fcntl(fd, fcntl.F_GETFD) & fcntl.FD_CLOEXEC,
4859 0)
Victor Stinnera3c18d02013-09-08 11:53:09 +02004860
4861
Victor Stinnerdaf45552013-08-28 00:53:59 +02004862 @unittest.skipUnless(hasattr(socket, "socketpair"),
4863 "need socket.socketpair()")
4864 def test_socketpair(self):
4865 s1, s2 = socket.socketpair()
4866 self.addCleanup(s1.close)
4867 self.addCleanup(s2.close)
4868 self.assertEqual(s1.get_inheritable(), False)
4869 self.assertEqual(s2.get_inheritable(), False)
Antoine Pitroub1c54962010-10-14 15:05:38 +00004870
4871
4872@unittest.skipUnless(hasattr(socket, "SOCK_NONBLOCK"),
4873 "SOCK_NONBLOCK not defined")
4874class NonblockConstantTest(unittest.TestCase):
4875 def checkNonblock(self, s, nonblock=True, timeout=0.0):
4876 if nonblock:
4877 self.assertTrue(s.type & socket.SOCK_NONBLOCK)
4878 self.assertEqual(s.gettimeout(), timeout)
4879 else:
4880 self.assertFalse(s.type & socket.SOCK_NONBLOCK)
4881 self.assertEqual(s.gettimeout(), None)
4882
Charles-François Natali239bb962011-06-03 12:55:15 +02004883 @support.requires_linux_version(2, 6, 28)
Antoine Pitroub1c54962010-10-14 15:05:38 +00004884 def test_SOCK_NONBLOCK(self):
4885 # a lot of it seems silly and redundant, but I wanted to test that
4886 # changing back and forth worked ok
Victor Stinner1d5eb342011-01-03 14:30:46 +00004887 with socket.socket(socket.AF_INET,
4888 socket.SOCK_STREAM | socket.SOCK_NONBLOCK) as s:
4889 self.checkNonblock(s)
4890 s.setblocking(1)
4891 self.checkNonblock(s, False)
4892 s.setblocking(0)
4893 self.checkNonblock(s)
4894 s.settimeout(None)
4895 self.checkNonblock(s, False)
4896 s.settimeout(2.0)
4897 self.checkNonblock(s, timeout=2.0)
4898 s.setblocking(1)
4899 self.checkNonblock(s, False)
Antoine Pitroub1c54962010-10-14 15:05:38 +00004900 # defaulttimeout
4901 t = socket.getdefaulttimeout()
4902 socket.setdefaulttimeout(0.0)
Victor Stinner1d5eb342011-01-03 14:30:46 +00004903 with socket.socket() as s:
4904 self.checkNonblock(s)
Antoine Pitroub1c54962010-10-14 15:05:38 +00004905 socket.setdefaulttimeout(None)
Victor Stinner1d5eb342011-01-03 14:30:46 +00004906 with socket.socket() as s:
4907 self.checkNonblock(s, False)
Antoine Pitroub1c54962010-10-14 15:05:38 +00004908 socket.setdefaulttimeout(2.0)
Victor Stinner1d5eb342011-01-03 14:30:46 +00004909 with socket.socket() as s:
4910 self.checkNonblock(s, timeout=2.0)
Antoine Pitroub1c54962010-10-14 15:05:38 +00004911 socket.setdefaulttimeout(None)
Victor Stinner1d5eb342011-01-03 14:30:46 +00004912 with socket.socket() as s:
4913 self.checkNonblock(s, False)
Antoine Pitroub1c54962010-10-14 15:05:38 +00004914 socket.setdefaulttimeout(t)
4915
Giampaolo Rodolàb383dbb2010-09-08 22:44:12 +00004916
Kristján Valur Jónsson10f383a2012-04-07 11:23:31 +00004917@unittest.skipUnless(os.name == "nt", "Windows specific")
4918@unittest.skipUnless(multiprocessing, "need multiprocessing")
4919class TestSocketSharing(SocketTCPTest):
4920 # This must be classmethod and not staticmethod or multiprocessing
4921 # won't be able to bootstrap it.
4922 @classmethod
4923 def remoteProcessServer(cls, q):
4924 # Recreate socket from shared data
4925 sdata = q.get()
4926 message = q.get()
4927
4928 s = socket.fromshare(sdata)
4929 s2, c = s.accept()
4930
4931 # Send the message
4932 s2.sendall(message)
4933 s2.close()
4934 s.close()
4935
4936 def testShare(self):
4937 # Transfer the listening server socket to another process
4938 # and service it from there.
4939
4940 # Create process:
4941 q = multiprocessing.Queue()
4942 p = multiprocessing.Process(target=self.remoteProcessServer, args=(q,))
4943 p.start()
4944
4945 # Get the shared socket data
4946 data = self.serv.share(p.pid)
4947
4948 # Pass the shared socket to the other process
4949 addr = self.serv.getsockname()
4950 self.serv.close()
4951 q.put(data)
4952
4953 # The data that the server will send us
4954 message = b"slapmahfro"
4955 q.put(message)
4956
4957 # Connect
4958 s = socket.create_connection(addr)
4959 # listen for the data
4960 m = []
4961 while True:
4962 data = s.recv(100)
4963 if not data:
4964 break
4965 m.append(data)
4966 s.close()
4967 received = b"".join(m)
4968 self.assertEqual(received, message)
4969 p.join()
4970
4971 def testShareLength(self):
4972 data = self.serv.share(os.getpid())
4973 self.assertRaises(ValueError, socket.fromshare, data[:-1])
4974 self.assertRaises(ValueError, socket.fromshare, data+b"foo")
4975
4976 def compareSockets(self, org, other):
4977 # socket sharing is expected to work only for blocking socket
4978 # since the internal python timout value isn't transfered.
4979 self.assertEqual(org.gettimeout(), None)
4980 self.assertEqual(org.gettimeout(), other.gettimeout())
4981
4982 self.assertEqual(org.family, other.family)
4983 self.assertEqual(org.type, other.type)
4984 # If the user specified "0" for proto, then
4985 # internally windows will have picked the correct value.
4986 # Python introspection on the socket however will still return
4987 # 0. For the shared socket, the python value is recreated
4988 # from the actual value, so it may not compare correctly.
4989 if org.proto != 0:
4990 self.assertEqual(org.proto, other.proto)
4991
4992 def testShareLocal(self):
4993 data = self.serv.share(os.getpid())
4994 s = socket.fromshare(data)
4995 try:
4996 self.compareSockets(self.serv, s)
4997 finally:
4998 s.close()
4999
5000 def testTypes(self):
5001 families = [socket.AF_INET, socket.AF_INET6]
5002 types = [socket.SOCK_STREAM, socket.SOCK_DGRAM]
5003 for f in families:
5004 for t in types:
Kristján Valur Jónsson52a11f12012-04-07 20:38:44 +00005005 try:
5006 source = socket.socket(f, t)
5007 except OSError:
5008 continue # This combination is not supported
Kristján Valur Jónsson10f383a2012-04-07 11:23:31 +00005009 try:
5010 data = source.share(os.getpid())
5011 shared = socket.fromshare(data)
5012 try:
5013 self.compareSockets(source, shared)
5014 finally:
5015 shared.close()
5016 finally:
5017 source.close()
5018
5019
Giampaolo Rodola'915d1412014-06-11 03:54:30 +02005020@unittest.skipUnless(thread, 'Threading required for this test.')
5021class SendfileUsingSendTest(ThreadedTCPSocketTest):
5022 """
5023 Test the send() implementation of socket.sendfile().
5024 """
5025
5026 FILESIZE = (10 * 1024 * 1024) # 10MB
5027 BUFSIZE = 8192
5028 FILEDATA = b""
5029 TIMEOUT = 2
5030
5031 @classmethod
5032 def setUpClass(cls):
5033 def chunks(total, step):
5034 assert total >= step
5035 while total > step:
5036 yield step
5037 total -= step
5038 if total:
5039 yield total
5040
5041 chunk = b"".join([random.choice(string.ascii_letters).encode()
5042 for i in range(cls.BUFSIZE)])
5043 with open(support.TESTFN, 'wb') as f:
5044 for csize in chunks(cls.FILESIZE, cls.BUFSIZE):
5045 f.write(chunk)
5046 with open(support.TESTFN, 'rb') as f:
5047 cls.FILEDATA = f.read()
5048 assert len(cls.FILEDATA) == cls.FILESIZE
5049
5050 @classmethod
5051 def tearDownClass(cls):
5052 support.unlink(support.TESTFN)
5053
5054 def accept_conn(self):
5055 self.serv.settimeout(self.TIMEOUT)
5056 conn, addr = self.serv.accept()
5057 conn.settimeout(self.TIMEOUT)
5058 self.addCleanup(conn.close)
5059 return conn
5060
5061 def recv_data(self, conn):
5062 received = []
5063 while True:
5064 chunk = conn.recv(self.BUFSIZE)
5065 if not chunk:
5066 break
5067 received.append(chunk)
5068 return b''.join(received)
5069
5070 def meth_from_sock(self, sock):
5071 # Depending on the mixin class being run return either send()
5072 # or sendfile() method implementation.
5073 return getattr(sock, "_sendfile_use_send")
5074
5075 # regular file
5076
5077 def _testRegularFile(self):
5078 address = self.serv.getsockname()
5079 file = open(support.TESTFN, 'rb')
5080 with socket.create_connection(address) as sock, file as file:
5081 meth = self.meth_from_sock(sock)
5082 sent = meth(file)
5083 self.assertEqual(sent, self.FILESIZE)
5084 self.assertEqual(file.tell(), self.FILESIZE)
5085
5086 def testRegularFile(self):
5087 conn = self.accept_conn()
5088 data = self.recv_data(conn)
5089 self.assertEqual(len(data), self.FILESIZE)
5090 self.assertEqual(data, self.FILEDATA)
5091
5092 # non regular file
5093
5094 def _testNonRegularFile(self):
5095 address = self.serv.getsockname()
5096 file = io.BytesIO(self.FILEDATA)
5097 with socket.create_connection(address) as sock, file as file:
5098 sent = sock.sendfile(file)
5099 self.assertEqual(sent, self.FILESIZE)
5100 self.assertEqual(file.tell(), self.FILESIZE)
5101 self.assertRaises(socket._GiveupOnSendfile,
5102 sock._sendfile_use_sendfile, file)
5103
5104 def testNonRegularFile(self):
5105 conn = self.accept_conn()
5106 data = self.recv_data(conn)
5107 self.assertEqual(len(data), self.FILESIZE)
5108 self.assertEqual(data, self.FILEDATA)
5109
5110 # empty file
5111
5112 def _testEmptyFileSend(self):
5113 address = self.serv.getsockname()
5114 filename = support.TESTFN + "2"
5115 with open(filename, 'wb'):
5116 self.addCleanup(support.unlink, filename)
5117 file = open(filename, 'rb')
5118 with socket.create_connection(address) as sock, file as file:
5119 meth = self.meth_from_sock(sock)
5120 sent = meth(file)
5121 self.assertEqual(sent, 0)
5122 self.assertEqual(file.tell(), 0)
5123
5124 def testEmptyFileSend(self):
5125 conn = self.accept_conn()
5126 data = self.recv_data(conn)
5127 self.assertEqual(data, b"")
5128
5129 # offset
5130
5131 def _testOffset(self):
5132 address = self.serv.getsockname()
5133 file = open(support.TESTFN, 'rb')
5134 with socket.create_connection(address) as sock, file as file:
5135 meth = self.meth_from_sock(sock)
5136 sent = meth(file, offset=5000)
5137 self.assertEqual(sent, self.FILESIZE - 5000)
5138 self.assertEqual(file.tell(), self.FILESIZE)
5139
5140 def testOffset(self):
5141 conn = self.accept_conn()
5142 data = self.recv_data(conn)
5143 self.assertEqual(len(data), self.FILESIZE - 5000)
5144 self.assertEqual(data, self.FILEDATA[5000:])
5145
5146 # count
5147
5148 def _testCount(self):
5149 address = self.serv.getsockname()
5150 file = open(support.TESTFN, 'rb')
5151 with socket.create_connection(address, timeout=2) as sock, file as file:
5152 count = 5000007
5153 meth = self.meth_from_sock(sock)
5154 sent = meth(file, count=count)
5155 self.assertEqual(sent, count)
5156 self.assertEqual(file.tell(), count)
5157
5158 def testCount(self):
5159 count = 5000007
5160 conn = self.accept_conn()
5161 data = self.recv_data(conn)
5162 self.assertEqual(len(data), count)
5163 self.assertEqual(data, self.FILEDATA[:count])
5164
5165 # count small
5166
5167 def _testCountSmall(self):
5168 address = self.serv.getsockname()
5169 file = open(support.TESTFN, 'rb')
5170 with socket.create_connection(address, timeout=2) as sock, file as file:
5171 count = 1
5172 meth = self.meth_from_sock(sock)
5173 sent = meth(file, count=count)
5174 self.assertEqual(sent, count)
5175 self.assertEqual(file.tell(), count)
5176
5177 def testCountSmall(self):
5178 count = 1
5179 conn = self.accept_conn()
5180 data = self.recv_data(conn)
5181 self.assertEqual(len(data), count)
5182 self.assertEqual(data, self.FILEDATA[:count])
5183
5184 # count + offset
5185
5186 def _testCountWithOffset(self):
5187 address = self.serv.getsockname()
5188 file = open(support.TESTFN, 'rb')
5189 with socket.create_connection(address, timeout=2) as sock, file as file:
5190 count = 100007
5191 meth = self.meth_from_sock(sock)
5192 sent = meth(file, offset=2007, count=count)
5193 self.assertEqual(sent, count)
5194 self.assertEqual(file.tell(), count + 2007)
5195
5196 def testCountWithOffset(self):
5197 count = 100007
5198 conn = self.accept_conn()
5199 data = self.recv_data(conn)
5200 self.assertEqual(len(data), count)
5201 self.assertEqual(data, self.FILEDATA[2007:count+2007])
5202
5203 # non blocking sockets are not supposed to work
5204
5205 def _testNonBlocking(self):
5206 address = self.serv.getsockname()
5207 file = open(support.TESTFN, 'rb')
5208 with socket.create_connection(address) as sock, file as file:
5209 sock.setblocking(False)
5210 meth = self.meth_from_sock(sock)
5211 self.assertRaises(ValueError, meth, file)
5212 self.assertRaises(ValueError, sock.sendfile, file)
5213
5214 def testNonBlocking(self):
5215 conn = self.accept_conn()
5216 if conn.recv(8192):
5217 self.fail('was not supposed to receive any data')
5218
5219 # timeout (non-triggered)
5220
5221 def _testWithTimeout(self):
5222 address = self.serv.getsockname()
5223 file = open(support.TESTFN, 'rb')
5224 with socket.create_connection(address, timeout=2) as sock, file as file:
5225 meth = self.meth_from_sock(sock)
5226 sent = meth(file)
5227 self.assertEqual(sent, self.FILESIZE)
5228
5229 def testWithTimeout(self):
5230 conn = self.accept_conn()
5231 data = self.recv_data(conn)
5232 self.assertEqual(len(data), self.FILESIZE)
5233 self.assertEqual(data, self.FILEDATA)
5234
5235 # timeout (triggered)
5236
5237 def _testWithTimeoutTriggeredSend(self):
5238 address = self.serv.getsockname()
5239 file = open(support.TESTFN, 'rb')
5240 with socket.create_connection(address, timeout=0.01) as sock, \
5241 file as file:
5242 meth = self.meth_from_sock(sock)
5243 self.assertRaises(socket.timeout, meth, file)
5244
5245 def testWithTimeoutTriggeredSend(self):
5246 conn = self.accept_conn()
5247 conn.recv(88192)
5248
5249 # errors
5250
5251 def _test_errors(self):
5252 pass
5253
5254 def test_errors(self):
5255 with open(support.TESTFN, 'rb') as file:
5256 with socket.socket(type=socket.SOCK_DGRAM) as s:
5257 meth = self.meth_from_sock(s)
5258 self.assertRaisesRegex(
5259 ValueError, "SOCK_STREAM", meth, file)
5260 with open(support.TESTFN, 'rt') as file:
5261 with socket.socket() as s:
5262 meth = self.meth_from_sock(s)
5263 self.assertRaisesRegex(
5264 ValueError, "binary mode", meth, file)
5265 with open(support.TESTFN, 'rb') as file:
5266 with socket.socket() as s:
5267 meth = self.meth_from_sock(s)
5268 self.assertRaisesRegex(TypeError, "positive integer",
5269 meth, file, count='2')
5270 self.assertRaisesRegex(TypeError, "positive integer",
5271 meth, file, count=0.1)
5272 self.assertRaisesRegex(ValueError, "positive integer",
5273 meth, file, count=0)
5274 self.assertRaisesRegex(ValueError, "positive integer",
5275 meth, file, count=-1)
5276
5277
5278@unittest.skipUnless(thread, 'Threading required for this test.')
5279@unittest.skipUnless(hasattr(os, "sendfile"),
5280 'os.sendfile() required for this test.')
5281class SendfileUsingSendfileTest(SendfileUsingSendTest):
5282 """
5283 Test the sendfile() implementation of socket.sendfile().
5284 """
5285 def meth_from_sock(self, sock):
5286 return getattr(sock, "_sendfile_use_sendfile")
5287
5288
Guido van Rossumb995eb72002-07-31 16:08:40 +00005289def test_main():
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005290 tests = [GeneralModuleTests, BasicTCPTest, TCPCloserTest, TCPTimeoutTest,
Ronald Oussoren94f25282010-05-05 19:11:21 +00005291 TestExceptions, BufferIOTest, BasicTCPTest2, BasicUDPTest, UDPTimeoutTest ]
Walter Dörwald21d3a322003-05-01 17:45:56 +00005292
5293 tests.extend([
5294 NonBlockingTCPTests,
5295 FileObjectClassTestCase,
5296 UnbufferedFileObjectClassTestCase,
5297 LineBufferedFileObjectClassTestCase,
Thomas Woutersb2137042007-02-01 18:02:27 +00005298 SmallBufferedFileObjectClassTestCase,
Antoine Pitrou834bd812010-10-13 16:17:14 +00005299 UnicodeReadFileObjectClassTestCase,
5300 UnicodeWriteFileObjectClassTestCase,
5301 UnicodeReadWriteFileObjectClassTestCase,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005302 NetworkConnectionNoServer,
5303 NetworkConnectionAttributesTest,
5304 NetworkConnectionBehaviourTest,
Giampaolo Rodolàb383dbb2010-09-08 22:44:12 +00005305 ContextManagersTest,
Victor Stinnerdaf45552013-08-28 00:53:59 +02005306 InheritanceTest,
Antoine Pitroub1c54962010-10-14 15:05:38 +00005307 NonblockConstantTest
Walter Dörwald21d3a322003-05-01 17:45:56 +00005308 ])
Serhiy Storchaka43767632013-11-03 21:31:38 +02005309 tests.append(BasicSocketPairTest)
5310 tests.append(TestUnixDomain)
5311 tests.append(TestLinuxAbstractNamespace)
5312 tests.extend([TIPCTest, TIPCThreadableTest])
Charles-François Natali47413c12011-10-06 19:47:44 +02005313 tests.extend([BasicCANTest, CANTest])
Charles-François Natali10b8cf42011-11-10 19:21:37 +01005314 tests.extend([BasicRDSTest, RDSTest])
Nick Coghlan96fe56a2011-08-22 11:55:57 +10005315 tests.extend([
5316 CmsgMacroTests,
5317 SendmsgUDPTest,
5318 RecvmsgUDPTest,
5319 RecvmsgIntoUDPTest,
5320 SendmsgUDP6Test,
5321 RecvmsgUDP6Test,
5322 RecvmsgRFC3542AncillaryUDP6Test,
5323 RecvmsgIntoRFC3542AncillaryUDP6Test,
5324 RecvmsgIntoUDP6Test,
5325 SendmsgTCPTest,
5326 RecvmsgTCPTest,
5327 RecvmsgIntoTCPTest,
5328 SendmsgSCTPStreamTest,
5329 RecvmsgSCTPStreamTest,
5330 RecvmsgIntoSCTPStreamTest,
5331 SendmsgUnixStreamTest,
5332 RecvmsgUnixStreamTest,
5333 RecvmsgIntoUnixStreamTest,
5334 RecvmsgSCMRightsStreamTest,
5335 RecvmsgIntoSCMRightsStreamTest,
5336 # These are slow when setitimer() is not available
5337 InterruptedRecvTimeoutTest,
5338 InterruptedSendTimeoutTest,
Kristján Valur Jónsson10f383a2012-04-07 11:23:31 +00005339 TestSocketSharing,
Giampaolo Rodola'915d1412014-06-11 03:54:30 +02005340 SendfileUsingSendTest,
5341 SendfileUsingSendfileTest,
Nick Coghlan96fe56a2011-08-22 11:55:57 +10005342 ])
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005343
Benjamin Petersonee8712c2008-05-20 21:35:26 +00005344 thread_info = support.threading_setup()
5345 support.run_unittest(*tests)
5346 support.threading_cleanup(*thread_info)
Guido van Rossum24e4af82002-06-12 19:18:08 +00005347
5348if __name__ == "__main__":
Guido van Rossumb995eb72002-07-31 16:08:40 +00005349 test_main()