blob: 4b047ee76ab790a4277e42b796f5a52cd2a105ea [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
Martin Panter46f50722016-05-26 05:35:26 +0000202 tests in pairs, where the test name is preceded with a
Guido van Rossum83ccb4e2002-06-18 18:35:13 +0000203 '_' 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):
Martin Panter69332c12016-08-04 13:07:31 +0000712 # Testing that sendto doesn't mask 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):
Martin Pantere26da7c2016-06-02 10:07:09 +00001307 # socketpair() is not strictly required, but it makes things easier.
Antoine Pitrou6d7df632010-09-27 17:52:25 +00001308 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
Berker Peksag3fe64d02016-02-18 17:34:00 +02001377 def test_makefile_mode(self):
1378 for mode in 'r', 'rb', 'rw', 'w', 'wb':
1379 with self.subTest(mode=mode):
1380 with socket.socket() as sock:
1381 with sock.makefile(mode) as fp:
1382 self.assertEqual(fp.mode, mode)
1383
1384 def test_makefile_invalid_mode(self):
1385 for mode in 'rt', 'x', '+', 'a':
1386 with self.subTest(mode=mode):
1387 with socket.socket() as sock:
1388 with self.assertRaisesRegex(ValueError, 'invalid mode'):
1389 sock.makefile(mode)
1390
Antoine Pitrou6d58d642011-03-20 23:56:36 +01001391 def test_pickle(self):
1392 sock = socket.socket()
1393 with sock:
1394 for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
1395 self.assertRaises(TypeError, pickle.dumps, sock, protocol)
Ethan Furman24e837f2015-03-18 17:27:57 -07001396 for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
1397 family = pickle.loads(pickle.dumps(socket.AF_INET, protocol))
1398 self.assertEqual(family, socket.AF_INET)
1399 type = pickle.loads(pickle.dumps(socket.SOCK_STREAM, protocol))
1400 self.assertEqual(type, socket.SOCK_STREAM)
Antoine Pitrou6d58d642011-03-20 23:56:36 +01001401
Serhiy Storchaka78980432013-01-15 01:12:17 +02001402 def test_listen_backlog(self):
1403 for backlog in 0, -1:
Charles-François Natali644b8f52014-05-22 19:45:39 +01001404 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as srv:
1405 srv.bind((HOST, 0))
1406 srv.listen(backlog)
1407
1408 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as srv:
Serhiy Storchaka78980432013-01-15 01:12:17 +02001409 srv.bind((HOST, 0))
Charles-François Natali644b8f52014-05-22 19:45:39 +01001410 srv.listen()
Serhiy Storchaka78980432013-01-15 01:12:17 +02001411
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001412 @support.cpython_only
1413 def test_listen_backlog_overflow(self):
Serhiy Storchaka78980432013-01-15 01:12:17 +02001414 # Issue 15989
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001415 import _testcapi
Antoine Pitrou1be815a2011-05-10 19:16:29 +02001416 srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1417 srv.bind((HOST, 0))
Serhiy Storchaka78980432013-01-15 01:12:17 +02001418 self.assertRaises(OverflowError, srv.listen, _testcapi.INT_MAX + 1)
Antoine Pitrou1be815a2011-05-10 19:16:29 +02001419 srv.close()
1420
Charles-François Natali42663332012-01-02 15:57:30 +01001421 @unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.')
Charles-François Natali366999a2012-01-02 15:47:29 +01001422 def test_flowinfo(self):
1423 self.assertRaises(OverflowError, socket.getnameinfo,
Charles-François Natalifcfb3242013-08-31 14:40:49 +02001424 (support.HOSTv6, 0, 0xffffffff), 0)
Charles-François Natali366999a2012-01-02 15:47:29 +01001425 with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s:
Charles-François Natalifcfb3242013-08-31 14:40:49 +02001426 self.assertRaises(OverflowError, s.bind, (support.HOSTv6, 0, -10))
Charles-François Natali366999a2012-01-02 15:47:29 +01001427
Eli Benderskyb2ff3cf2013-08-31 15:13:30 -07001428 def test_str_for_enums(self):
1429 # Make sure that the AF_* and SOCK_* constants have enum-like string
1430 # reprs.
1431 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
1432 self.assertEqual(str(s.family), 'AddressFamily.AF_INET')
Ethan Furman7184bac2014-10-14 18:56:53 -07001433 self.assertEqual(str(s.type), 'SocketKind.SOCK_STREAM')
Eli Benderskyb2ff3cf2013-08-31 15:13:30 -07001434
1435 @unittest.skipIf(os.name == 'nt', 'Will not work on Windows')
1436 def test_uknown_socket_family_repr(self):
1437 # Test that when created with a family that's not one of the known
1438 # AF_*/SOCK_* constants, socket.family just returns the number.
1439 #
1440 # To do this we fool socket.socket into believing it already has an
1441 # open fd because on this path it doesn't actually verify the family and
1442 # type and populates the socket object.
1443 #
1444 # On Windows this trick won't work, so the test is skipped.
1445 fd, _ = tempfile.mkstemp()
1446 with socket.socket(family=42424, type=13331, fileno=fd) as s:
1447 self.assertEqual(s.family, 42424)
1448 self.assertEqual(s.type, 13331)
Antoine Pitrou6d7df632010-09-27 17:52:25 +00001449
Charles-François Natali47413c12011-10-06 19:47:44 +02001450@unittest.skipUnless(HAVE_SOCKET_CAN, 'SocketCan required for this test.')
1451class BasicCANTest(unittest.TestCase):
1452
1453 def testCrucialConstants(self):
1454 socket.AF_CAN
1455 socket.PF_CAN
1456 socket.CAN_RAW
1457
Charles-François Natali773e42d2013-02-05 19:42:01 +01001458 @unittest.skipUnless(hasattr(socket, "CAN_BCM"),
1459 'socket.CAN_BCM required for this test.')
1460 def testBCMConstants(self):
1461 socket.CAN_BCM
1462
1463 # opcodes
1464 socket.CAN_BCM_TX_SETUP # create (cyclic) transmission task
1465 socket.CAN_BCM_TX_DELETE # remove (cyclic) transmission task
1466 socket.CAN_BCM_TX_READ # read properties of (cyclic) transmission task
1467 socket.CAN_BCM_TX_SEND # send one CAN frame
1468 socket.CAN_BCM_RX_SETUP # create RX content filter subscription
1469 socket.CAN_BCM_RX_DELETE # remove RX content filter subscription
1470 socket.CAN_BCM_RX_READ # read properties of RX content filter subscription
1471 socket.CAN_BCM_TX_STATUS # reply to TX_READ request
1472 socket.CAN_BCM_TX_EXPIRED # notification on performed transmissions (count=0)
1473 socket.CAN_BCM_RX_STATUS # reply to RX_READ request
1474 socket.CAN_BCM_RX_TIMEOUT # cyclic message is absent
1475 socket.CAN_BCM_RX_CHANGED # updated CAN frame (detected content change)
1476
Charles-François Natali47413c12011-10-06 19:47:44 +02001477 def testCreateSocket(self):
1478 with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
1479 pass
1480
Charles-François Natali773e42d2013-02-05 19:42:01 +01001481 @unittest.skipUnless(hasattr(socket, "CAN_BCM"),
1482 'socket.CAN_BCM required for this test.')
1483 def testCreateBCMSocket(self):
1484 with socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_BCM) as s:
1485 pass
1486
Charles-François Natali47413c12011-10-06 19:47:44 +02001487 def testBindAny(self):
1488 with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
1489 s.bind(('', ))
1490
1491 def testTooLongInterfaceName(self):
1492 # most systems limit IFNAMSIZ to 16, take 1024 to be sure
1493 with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
Andrew Svetlov0832af62012-12-18 23:10:48 +02001494 self.assertRaisesRegex(OSError, 'interface name too long',
Antoine Pitrouffa547e2011-10-11 22:43:37 +02001495 s.bind, ('x' * 1024,))
Charles-François Natali47413c12011-10-06 19:47:44 +02001496
1497 @unittest.skipUnless(hasattr(socket, "CAN_RAW_LOOPBACK"),
1498 'socket.CAN_RAW_LOOPBACK required for this test.')
1499 def testLoopback(self):
1500 with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
1501 for loopback in (0, 1):
1502 s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_LOOPBACK,
1503 loopback)
1504 self.assertEqual(loopback,
1505 s.getsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_LOOPBACK))
1506
1507 @unittest.skipUnless(hasattr(socket, "CAN_RAW_FILTER"),
1508 'socket.CAN_RAW_FILTER required for this test.')
1509 def testFilter(self):
1510 can_id, can_mask = 0x200, 0x700
1511 can_filter = struct.pack("=II", can_id, can_mask)
1512 with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
1513 s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FILTER, can_filter)
1514 self.assertEqual(can_filter,
1515 s.getsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FILTER, 8))
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02001516 s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FILTER, bytearray(can_filter))
Charles-François Natali47413c12011-10-06 19:47:44 +02001517
1518
1519@unittest.skipUnless(HAVE_SOCKET_CAN, 'SocketCan required for this test.')
Terry Jan Reedya40e6b02014-06-13 15:20:45 -04001520@unittest.skipUnless(thread, 'Threading required for this test.')
Charles-François Natali47413c12011-10-06 19:47:44 +02001521class CANTest(ThreadedCANSocketTest):
1522
Charles-François Natali47413c12011-10-06 19:47:44 +02001523 def __init__(self, methodName='runTest'):
1524 ThreadedCANSocketTest.__init__(self, methodName=methodName)
1525
1526 @classmethod
1527 def build_can_frame(cls, can_id, data):
1528 """Build a CAN frame."""
1529 can_dlc = len(data)
1530 data = data.ljust(8, b'\x00')
1531 return struct.pack(cls.can_frame_fmt, can_id, can_dlc, data)
1532
1533 @classmethod
1534 def dissect_can_frame(cls, frame):
1535 """Dissect a CAN frame."""
1536 can_id, can_dlc, data = struct.unpack(cls.can_frame_fmt, frame)
1537 return (can_id, can_dlc, data[:can_dlc])
1538
1539 def testSendFrame(self):
1540 cf, addr = self.s.recvfrom(self.bufsize)
1541 self.assertEqual(self.cf, cf)
1542 self.assertEqual(addr[0], self.interface)
1543 self.assertEqual(addr[1], socket.AF_CAN)
1544
1545 def _testSendFrame(self):
1546 self.cf = self.build_can_frame(0x00, b'\x01\x02\x03\x04\x05')
1547 self.cli.send(self.cf)
1548
1549 def testSendMaxFrame(self):
1550 cf, addr = self.s.recvfrom(self.bufsize)
1551 self.assertEqual(self.cf, cf)
1552
1553 def _testSendMaxFrame(self):
1554 self.cf = self.build_can_frame(0x00, b'\x07' * 8)
1555 self.cli.send(self.cf)
1556
1557 def testSendMultiFrames(self):
1558 cf, addr = self.s.recvfrom(self.bufsize)
1559 self.assertEqual(self.cf1, cf)
1560
1561 cf, addr = self.s.recvfrom(self.bufsize)
1562 self.assertEqual(self.cf2, cf)
1563
1564 def _testSendMultiFrames(self):
1565 self.cf1 = self.build_can_frame(0x07, b'\x44\x33\x22\x11')
1566 self.cli.send(self.cf1)
1567
1568 self.cf2 = self.build_can_frame(0x12, b'\x99\x22\x33')
1569 self.cli.send(self.cf2)
1570
Charles-François Natali773e42d2013-02-05 19:42:01 +01001571 @unittest.skipUnless(hasattr(socket, "CAN_BCM"),
1572 'socket.CAN_BCM required for this test.')
1573 def _testBCM(self):
1574 cf, addr = self.cli.recvfrom(self.bufsize)
1575 self.assertEqual(self.cf, cf)
1576 can_id, can_dlc, data = self.dissect_can_frame(cf)
1577 self.assertEqual(self.can_id, can_id)
1578 self.assertEqual(self.data, data)
1579
1580 @unittest.skipUnless(hasattr(socket, "CAN_BCM"),
1581 'socket.CAN_BCM required for this test.')
1582 def testBCM(self):
1583 bcm = socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_BCM)
1584 self.addCleanup(bcm.close)
1585 bcm.connect((self.interface,))
1586 self.can_id = 0x123
1587 self.data = bytes([0xc0, 0xff, 0xee])
1588 self.cf = self.build_can_frame(self.can_id, self.data)
1589 opcode = socket.CAN_BCM_TX_SEND
1590 flags = 0
1591 count = 0
1592 ival1_seconds = ival1_usec = ival2_seconds = ival2_usec = 0
1593 bcm_can_id = 0x0222
1594 nframes = 1
1595 assert len(self.cf) == 16
1596 header = struct.pack(self.bcm_cmd_msg_fmt,
1597 opcode,
1598 flags,
1599 count,
1600 ival1_seconds,
1601 ival1_usec,
1602 ival2_seconds,
1603 ival2_usec,
1604 bcm_can_id,
1605 nframes,
1606 )
1607 header_plus_frame = header + self.cf
1608 bytes_sent = bcm.send(header_plus_frame)
1609 self.assertEqual(bytes_sent, len(header_plus_frame))
1610
Charles-François Natali47413c12011-10-06 19:47:44 +02001611
Charles-François Natali10b8cf42011-11-10 19:21:37 +01001612@unittest.skipUnless(HAVE_SOCKET_RDS, 'RDS sockets required for this test.')
1613class BasicRDSTest(unittest.TestCase):
1614
1615 def testCrucialConstants(self):
1616 socket.AF_RDS
1617 socket.PF_RDS
1618
1619 def testCreateSocket(self):
1620 with socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0) as s:
1621 pass
1622
1623 def testSocketBufferSize(self):
1624 bufsize = 16384
1625 with socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0) as s:
1626 s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, bufsize)
1627 s.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, bufsize)
1628
1629
1630@unittest.skipUnless(HAVE_SOCKET_RDS, 'RDS sockets required for this test.')
1631@unittest.skipUnless(thread, 'Threading required for this test.')
1632class RDSTest(ThreadedRDSSocketTest):
1633
1634 def __init__(self, methodName='runTest'):
1635 ThreadedRDSSocketTest.__init__(self, methodName=methodName)
1636
Charles-François Natali240c55f2011-11-10 20:33:36 +01001637 def setUp(self):
1638 super().setUp()
1639 self.evt = threading.Event()
1640
Charles-François Natali10b8cf42011-11-10 19:21:37 +01001641 def testSendAndRecv(self):
1642 data, addr = self.serv.recvfrom(self.bufsize)
1643 self.assertEqual(self.data, data)
1644 self.assertEqual(self.cli_addr, addr)
1645
1646 def _testSendAndRecv(self):
1647 self.data = b'spam'
1648 self.cli.sendto(self.data, 0, (HOST, self.port))
1649
1650 def testPeek(self):
1651 data, addr = self.serv.recvfrom(self.bufsize, socket.MSG_PEEK)
1652 self.assertEqual(self.data, data)
1653 data, addr = self.serv.recvfrom(self.bufsize)
1654 self.assertEqual(self.data, data)
1655
1656 def _testPeek(self):
1657 self.data = b'spam'
1658 self.cli.sendto(self.data, 0, (HOST, self.port))
1659
1660 @requireAttrs(socket.socket, 'recvmsg')
1661 def testSendAndRecvMsg(self):
1662 data, ancdata, msg_flags, addr = self.serv.recvmsg(self.bufsize)
1663 self.assertEqual(self.data, data)
1664
1665 @requireAttrs(socket.socket, 'sendmsg')
1666 def _testSendAndRecvMsg(self):
1667 self.data = b'hello ' * 10
1668 self.cli.sendmsg([self.data], (), 0, (HOST, self.port))
1669
1670 def testSendAndRecvMulti(self):
1671 data, addr = self.serv.recvfrom(self.bufsize)
1672 self.assertEqual(self.data1, data)
1673
1674 data, addr = self.serv.recvfrom(self.bufsize)
1675 self.assertEqual(self.data2, data)
1676
1677 def _testSendAndRecvMulti(self):
1678 self.data1 = b'bacon'
1679 self.cli.sendto(self.data1, 0, (HOST, self.port))
1680
1681 self.data2 = b'egg'
1682 self.cli.sendto(self.data2, 0, (HOST, self.port))
1683
1684 def testSelect(self):
1685 r, w, x = select.select([self.serv], [], [], 3.0)
1686 self.assertIn(self.serv, r)
1687 data, addr = self.serv.recvfrom(self.bufsize)
1688 self.assertEqual(self.data, data)
1689
1690 def _testSelect(self):
1691 self.data = b'select'
1692 self.cli.sendto(self.data, 0, (HOST, self.port))
1693
1694 def testCongestion(self):
1695 # wait until the sender is done
1696 self.evt.wait()
1697
1698 def _testCongestion(self):
1699 # test the behavior in case of congestion
1700 self.data = b'fill'
1701 self.cli.setblocking(False)
1702 try:
1703 # try to lower the receiver's socket buffer size
1704 self.cli.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 16384)
1705 except OSError:
1706 pass
1707 with self.assertRaises(OSError) as cm:
1708 try:
1709 # fill the receiver's socket buffer
1710 while True:
1711 self.cli.sendto(self.data, 0, (HOST, self.port))
1712 finally:
1713 # signal the receiver we're done
1714 self.evt.set()
1715 # sendto() should have failed with ENOBUFS
1716 self.assertEqual(cm.exception.errno, errno.ENOBUFS)
1717 # and we should have received a congestion notification through poll
1718 r, w, x = select.select([self.serv], [], [], 3.0)
1719 self.assertIn(self.serv, r)
1720
1721
Victor Stinner45df8202010-04-28 22:31:17 +00001722@unittest.skipUnless(thread, 'Threading required for this test.')
Guido van Rossum24e4af82002-06-12 19:18:08 +00001723class BasicTCPTest(SocketConnectedTest):
1724
1725 def __init__(self, methodName='runTest'):
1726 SocketConnectedTest.__init__(self, methodName=methodName)
1727
1728 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00001729 # Testing large receive over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +00001730 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +00001731 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001732
1733 def _testRecv(self):
1734 self.serv_conn.send(MSG)
1735
1736 def testOverFlowRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00001737 # Testing receive in chunks over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +00001738 seg1 = self.cli_conn.recv(len(MSG) - 3)
1739 seg2 = self.cli_conn.recv(1024)
Guido van Rossumab659962002-06-12 21:29:43 +00001740 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +00001741 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001742
1743 def _testOverFlowRecv(self):
1744 self.serv_conn.send(MSG)
1745
1746 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00001747 # Testing large recvfrom() over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +00001748 msg, addr = self.cli_conn.recvfrom(1024)
Guido van Rossum76489682002-06-12 20:38:30 +00001749 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001750
1751 def _testRecvFrom(self):
1752 self.serv_conn.send(MSG)
1753
1754 def testOverFlowRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00001755 # Testing recvfrom() in chunks over TCP
Guido van Rossum24e4af82002-06-12 19:18:08 +00001756 seg1, addr = self.cli_conn.recvfrom(len(MSG)-3)
1757 seg2, addr = self.cli_conn.recvfrom(1024)
Guido van Rossumab659962002-06-12 21:29:43 +00001758 msg = seg1 + seg2
Guido van Rossum76489682002-06-12 20:38:30 +00001759 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001760
1761 def _testOverFlowRecvFrom(self):
1762 self.serv_conn.send(MSG)
1763
1764 def testSendAll(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00001765 # Testing sendall() with a 2048 byte string over TCP
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001766 msg = b''
Guido van Rossum24e4af82002-06-12 19:18:08 +00001767 while 1:
1768 read = self.cli_conn.recv(1024)
1769 if not read:
1770 break
Guido van Rossume531e292002-08-08 20:28:34 +00001771 msg += read
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001772 self.assertEqual(msg, b'f' * 2048)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001773
1774 def _testSendAll(self):
Guido van Rossum7d0a8262007-05-21 23:13:11 +00001775 big_chunk = b'f' * 2048
Guido van Rossum24e4af82002-06-12 19:18:08 +00001776 self.serv_conn.sendall(big_chunk)
1777
1778 def testFromFd(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00001779 # Testing fromfd()
Guido van Rossum24e4af82002-06-12 19:18:08 +00001780 fd = self.cli_conn.fileno()
1781 sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
Brian Curtin21ebbb72010-11-02 02:07:09 +00001782 self.addCleanup(sock.close)
Antoine Pitrou9e0b8642010-09-14 18:00:02 +00001783 self.assertIsInstance(sock, socket.socket)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001784 msg = sock.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +00001785 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001786
1787 def _testFromFd(self):
1788 self.serv_conn.send(MSG)
1789
Guido van Rossum39eb8fa2007-11-16 01:24:05 +00001790 def testDup(self):
1791 # Testing dup()
1792 sock = self.cli_conn.dup()
Brian Curtin21ebbb72010-11-02 02:07:09 +00001793 self.addCleanup(sock.close)
Guido van Rossum39eb8fa2007-11-16 01:24:05 +00001794 msg = sock.recv(1024)
1795 self.assertEqual(msg, MSG)
1796
1797 def _testDup(self):
1798 self.serv_conn.send(MSG)
1799
Guido van Rossum24e4af82002-06-12 19:18:08 +00001800 def testShutdown(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00001801 # Testing shutdown()
Guido van Rossum24e4af82002-06-12 19:18:08 +00001802 msg = self.cli_conn.recv(1024)
Guido van Rossum76489682002-06-12 20:38:30 +00001803 self.assertEqual(msg, MSG)
Mark Dickinson29500f62009-01-15 15:36:10 +00001804 # wait for _testShutdown to finish: on OS X, when the server
1805 # closes the connection the client also becomes disconnected,
1806 # and the client's shutdown call will fail. (Issue #4397.)
1807 self.done.wait()
Guido van Rossum24e4af82002-06-12 19:18:08 +00001808
1809 def _testShutdown(self):
1810 self.serv_conn.send(MSG)
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001811 self.serv_conn.shutdown(2)
1812
1813 testShutdown_overflow = support.cpython_only(testShutdown)
1814
1815 @support.cpython_only
1816 def _testShutdown_overflow(self):
1817 import _testcapi
1818 self.serv_conn.send(MSG)
Serhiy Storchaka78980432013-01-15 01:12:17 +02001819 # Issue 15989
1820 self.assertRaises(OverflowError, self.serv_conn.shutdown,
1821 _testcapi.INT_MAX + 1)
1822 self.assertRaises(OverflowError, self.serv_conn.shutdown,
1823 2 + (_testcapi.UINT_MAX + 1))
Guido van Rossum24e4af82002-06-12 19:18:08 +00001824 self.serv_conn.shutdown(2)
1825
Antoine Pitrou6e451df2010-08-09 20:39:54 +00001826 def testDetach(self):
1827 # Testing detach()
1828 fileno = self.cli_conn.fileno()
1829 f = self.cli_conn.detach()
1830 self.assertEqual(f, fileno)
1831 # cli_conn cannot be used anymore...
Antoine Pitrou70deb3d2012-04-01 01:00:17 +02001832 self.assertTrue(self.cli_conn._closed)
Andrew Svetlov0832af62012-12-18 23:10:48 +02001833 self.assertRaises(OSError, self.cli_conn.recv, 1024)
Antoine Pitroue43f9d02010-08-08 23:24:50 +00001834 self.cli_conn.close()
Antoine Pitrou6e451df2010-08-09 20:39:54 +00001835 # ...but we can create another socket using the (still open)
1836 # file descriptor
Antoine Pitroue43f9d02010-08-08 23:24:50 +00001837 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, fileno=f)
Brian Curtin21ebbb72010-11-02 02:07:09 +00001838 self.addCleanup(sock.close)
Antoine Pitroue43f9d02010-08-08 23:24:50 +00001839 msg = sock.recv(1024)
1840 self.assertEqual(msg, MSG)
1841
Antoine Pitrou6e451df2010-08-09 20:39:54 +00001842 def _testDetach(self):
Antoine Pitroue43f9d02010-08-08 23:24:50 +00001843 self.serv_conn.send(MSG)
1844
Victor Stinner45df8202010-04-28 22:31:17 +00001845@unittest.skipUnless(thread, 'Threading required for this test.')
Guido van Rossum24e4af82002-06-12 19:18:08 +00001846class BasicUDPTest(ThreadedUDPSocketTest):
1847
1848 def __init__(self, methodName='runTest'):
1849 ThreadedUDPSocketTest.__init__(self, methodName=methodName)
1850
1851 def testSendtoAndRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00001852 # Testing sendto() and Recv() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +00001853 msg = self.serv.recv(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +00001854 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001855
1856 def _testSendtoAndRecv(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001857 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +00001858
Guido van Rossum1c938012002-06-12 21:17:20 +00001859 def testRecvFrom(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00001860 # Testing recvfrom() over UDP
Guido van Rossum24e4af82002-06-12 19:18:08 +00001861 msg, addr = self.serv.recvfrom(len(MSG))
Guido van Rossum76489682002-06-12 20:38:30 +00001862 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +00001863
Guido van Rossum1c938012002-06-12 21:17:20 +00001864 def _testRecvFrom(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001865 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +00001866
Guido van Rossumd8faa362007-04-27 19:54:29 +00001867 def testRecvFromNegative(self):
1868 # Negative lengths passed to recvfrom should give ValueError.
1869 self.assertRaises(ValueError, self.serv.recvfrom, -1)
1870
1871 def _testRecvFromNegative(self):
Christian Heimes5e696852008-04-09 08:37:03 +00001872 self.cli.sendto(MSG, 0, (HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001873
Nick Coghlan96fe56a2011-08-22 11:55:57 +10001874# Tests for the sendmsg()/recvmsg() interface. Where possible, the
1875# same test code is used with different families and types of socket
1876# (e.g. stream, datagram), and tests using recvmsg() are repeated
1877# using recvmsg_into().
1878#
1879# The generic test classes such as SendmsgTests and
1880# RecvmsgGenericTests inherit from SendrecvmsgBase and expect to be
1881# supplied with sockets cli_sock and serv_sock representing the
1882# client's and the server's end of the connection respectively, and
1883# attributes cli_addr and serv_addr holding their (numeric where
1884# appropriate) addresses.
1885#
1886# The final concrete test classes combine these with subclasses of
1887# SocketTestBase which set up client and server sockets of a specific
1888# type, and with subclasses of SendrecvmsgBase such as
1889# SendrecvmsgDgramBase and SendrecvmsgConnectedBase which map these
1890# sockets to cli_sock and serv_sock and override the methods and
1891# attributes of SendrecvmsgBase to fill in destination addresses if
1892# needed when sending, check for specific flags in msg_flags, etc.
1893#
1894# RecvmsgIntoMixin provides a version of doRecvmsg() implemented using
1895# recvmsg_into().
1896
1897# XXX: like the other datagram (UDP) tests in this module, the code
1898# here assumes that datagram delivery on the local machine will be
1899# reliable.
1900
1901class SendrecvmsgBase(ThreadSafeCleanupTestCase):
1902 # Base class for sendmsg()/recvmsg() tests.
1903
1904 # Time in seconds to wait before considering a test failed, or
1905 # None for no timeout. Not all tests actually set a timeout.
1906 fail_timeout = 3.0
1907
1908 def setUp(self):
1909 self.misc_event = threading.Event()
1910 super().setUp()
1911
1912 def sendToServer(self, msg):
1913 # Send msg to the server.
1914 return self.cli_sock.send(msg)
1915
1916 # Tuple of alternative default arguments for sendmsg() when called
1917 # via sendmsgToServer() (e.g. to include a destination address).
1918 sendmsg_to_server_defaults = ()
1919
1920 def sendmsgToServer(self, *args):
1921 # Call sendmsg() on self.cli_sock with the given arguments,
1922 # filling in any arguments which are not supplied with the
1923 # corresponding items of self.sendmsg_to_server_defaults, if
1924 # any.
1925 return self.cli_sock.sendmsg(
1926 *(args + self.sendmsg_to_server_defaults[len(args):]))
1927
1928 def doRecvmsg(self, sock, bufsize, *args):
1929 # Call recvmsg() on sock with given arguments and return its
1930 # result. Should be used for tests which can use either
1931 # recvmsg() or recvmsg_into() - RecvmsgIntoMixin overrides
1932 # this method with one which emulates it using recvmsg_into(),
1933 # thus allowing the same test to be used for both methods.
1934 result = sock.recvmsg(bufsize, *args)
1935 self.registerRecvmsgResult(result)
1936 return result
1937
1938 def registerRecvmsgResult(self, result):
1939 # Called by doRecvmsg() with the return value of recvmsg() or
1940 # recvmsg_into(). Can be overridden to arrange cleanup based
1941 # on the returned ancillary data, for instance.
1942 pass
1943
1944 def checkRecvmsgAddress(self, addr1, addr2):
1945 # Called to compare the received address with the address of
1946 # the peer.
1947 self.assertEqual(addr1, addr2)
1948
1949 # Flags that are normally unset in msg_flags
1950 msg_flags_common_unset = 0
1951 for name in ("MSG_CTRUNC", "MSG_OOB"):
1952 msg_flags_common_unset |= getattr(socket, name, 0)
1953
1954 # Flags that are normally set
1955 msg_flags_common_set = 0
1956
1957 # Flags set when a complete record has been received (e.g. MSG_EOR
1958 # for SCTP)
1959 msg_flags_eor_indicator = 0
1960
1961 # Flags set when a complete record has not been received
1962 # (e.g. MSG_TRUNC for datagram sockets)
1963 msg_flags_non_eor_indicator = 0
1964
1965 def checkFlags(self, flags, eor=None, checkset=0, checkunset=0, ignore=0):
1966 # Method to check the value of msg_flags returned by recvmsg[_into]().
1967 #
1968 # Checks that all bits in msg_flags_common_set attribute are
1969 # set in "flags" and all bits in msg_flags_common_unset are
1970 # unset.
1971 #
1972 # The "eor" argument specifies whether the flags should
1973 # indicate that a full record (or datagram) has been received.
1974 # If "eor" is None, no checks are done; otherwise, checks
1975 # that:
1976 #
1977 # * if "eor" is true, all bits in msg_flags_eor_indicator are
1978 # set and all bits in msg_flags_non_eor_indicator are unset
1979 #
1980 # * if "eor" is false, all bits in msg_flags_non_eor_indicator
1981 # are set and all bits in msg_flags_eor_indicator are unset
1982 #
1983 # If "checkset" and/or "checkunset" are supplied, they require
1984 # the given bits to be set or unset respectively, overriding
1985 # what the attributes require for those bits.
1986 #
1987 # If any bits are set in "ignore", they will not be checked,
1988 # regardless of the other inputs.
1989 #
1990 # Will raise Exception if the inputs require a bit to be both
1991 # set and unset, and it is not ignored.
1992
1993 defaultset = self.msg_flags_common_set
1994 defaultunset = self.msg_flags_common_unset
1995
1996 if eor:
1997 defaultset |= self.msg_flags_eor_indicator
1998 defaultunset |= self.msg_flags_non_eor_indicator
1999 elif eor is not None:
2000 defaultset |= self.msg_flags_non_eor_indicator
2001 defaultunset |= self.msg_flags_eor_indicator
2002
2003 # Function arguments override defaults
2004 defaultset &= ~checkunset
2005 defaultunset &= ~checkset
2006
2007 # Merge arguments with remaining defaults, and check for conflicts
2008 checkset |= defaultset
2009 checkunset |= defaultunset
2010 inboth = checkset & checkunset & ~ignore
2011 if inboth:
2012 raise Exception("contradictory set, unset requirements for flags "
2013 "{0:#x}".format(inboth))
2014
2015 # Compare with given msg_flags value
2016 mask = (checkset | checkunset) & ~ignore
2017 self.assertEqual(flags & mask, checkset & mask)
2018
2019
2020class RecvmsgIntoMixin(SendrecvmsgBase):
2021 # Mixin to implement doRecvmsg() using recvmsg_into().
2022
2023 def doRecvmsg(self, sock, bufsize, *args):
2024 buf = bytearray(bufsize)
2025 result = sock.recvmsg_into([buf], *args)
2026 self.registerRecvmsgResult(result)
2027 self.assertGreaterEqual(result[0], 0)
2028 self.assertLessEqual(result[0], bufsize)
2029 return (bytes(buf[:result[0]]),) + result[1:]
2030
2031
2032class SendrecvmsgDgramFlagsBase(SendrecvmsgBase):
2033 # Defines flags to be checked in msg_flags for datagram sockets.
2034
2035 @property
2036 def msg_flags_non_eor_indicator(self):
2037 return super().msg_flags_non_eor_indicator | socket.MSG_TRUNC
2038
2039
2040class SendrecvmsgSCTPFlagsBase(SendrecvmsgBase):
2041 # Defines flags to be checked in msg_flags for SCTP sockets.
2042
2043 @property
2044 def msg_flags_eor_indicator(self):
2045 return super().msg_flags_eor_indicator | socket.MSG_EOR
2046
2047
2048class SendrecvmsgConnectionlessBase(SendrecvmsgBase):
2049 # Base class for tests on connectionless-mode sockets. Users must
2050 # supply sockets on attributes cli and serv to be mapped to
2051 # cli_sock and serv_sock respectively.
2052
2053 @property
2054 def serv_sock(self):
2055 return self.serv
2056
2057 @property
2058 def cli_sock(self):
2059 return self.cli
2060
2061 @property
2062 def sendmsg_to_server_defaults(self):
2063 return ([], [], 0, self.serv_addr)
2064
2065 def sendToServer(self, msg):
2066 return self.cli_sock.sendto(msg, self.serv_addr)
2067
2068
2069class SendrecvmsgConnectedBase(SendrecvmsgBase):
2070 # Base class for tests on connected sockets. Users must supply
2071 # sockets on attributes serv_conn and cli_conn (representing the
2072 # connections *to* the server and the client), to be mapped to
2073 # cli_sock and serv_sock respectively.
2074
2075 @property
2076 def serv_sock(self):
2077 return self.cli_conn
2078
2079 @property
2080 def cli_sock(self):
2081 return self.serv_conn
2082
2083 def checkRecvmsgAddress(self, addr1, addr2):
2084 # Address is currently "unspecified" for a connected socket,
2085 # so we don't examine it
2086 pass
2087
2088
2089class SendrecvmsgServerTimeoutBase(SendrecvmsgBase):
2090 # Base class to set a timeout on server's socket.
2091
2092 def setUp(self):
2093 super().setUp()
2094 self.serv_sock.settimeout(self.fail_timeout)
2095
2096
2097class SendmsgTests(SendrecvmsgServerTimeoutBase):
2098 # Tests for sendmsg() which can use any socket type and do not
2099 # involve recvmsg() or recvmsg_into().
2100
2101 def testSendmsg(self):
2102 # Send a simple message with sendmsg().
2103 self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
2104
2105 def _testSendmsg(self):
2106 self.assertEqual(self.sendmsgToServer([MSG]), len(MSG))
2107
2108 def testSendmsgDataGenerator(self):
2109 # Send from buffer obtained from a generator (not a sequence).
2110 self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
2111
2112 def _testSendmsgDataGenerator(self):
2113 self.assertEqual(self.sendmsgToServer((o for o in [MSG])),
2114 len(MSG))
2115
2116 def testSendmsgAncillaryGenerator(self):
2117 # Gather (empty) ancillary data from a generator.
2118 self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
2119
2120 def _testSendmsgAncillaryGenerator(self):
2121 self.assertEqual(self.sendmsgToServer([MSG], (o for o in [])),
2122 len(MSG))
2123
2124 def testSendmsgArray(self):
2125 # Send data from an array instead of the usual bytes object.
2126 self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
2127
2128 def _testSendmsgArray(self):
2129 self.assertEqual(self.sendmsgToServer([array.array("B", MSG)]),
2130 len(MSG))
2131
2132 def testSendmsgGather(self):
2133 # Send message data from more than one buffer (gather write).
2134 self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
2135
2136 def _testSendmsgGather(self):
2137 self.assertEqual(self.sendmsgToServer([MSG[:3], MSG[3:]]), len(MSG))
2138
2139 def testSendmsgBadArgs(self):
2140 # Check that sendmsg() rejects invalid arguments.
2141 self.assertEqual(self.serv_sock.recv(1000), b"done")
2142
2143 def _testSendmsgBadArgs(self):
2144 self.assertRaises(TypeError, self.cli_sock.sendmsg)
2145 self.assertRaises(TypeError, self.sendmsgToServer,
2146 b"not in an iterable")
2147 self.assertRaises(TypeError, self.sendmsgToServer,
2148 object())
2149 self.assertRaises(TypeError, self.sendmsgToServer,
2150 [object()])
2151 self.assertRaises(TypeError, self.sendmsgToServer,
2152 [MSG, object()])
2153 self.assertRaises(TypeError, self.sendmsgToServer,
2154 [MSG], object())
2155 self.assertRaises(TypeError, self.sendmsgToServer,
2156 [MSG], [], object())
2157 self.assertRaises(TypeError, self.sendmsgToServer,
2158 [MSG], [], 0, object())
2159 self.sendToServer(b"done")
2160
2161 def testSendmsgBadCmsg(self):
2162 # Check that invalid ancillary data items are rejected.
2163 self.assertEqual(self.serv_sock.recv(1000), b"done")
2164
2165 def _testSendmsgBadCmsg(self):
2166 self.assertRaises(TypeError, self.sendmsgToServer,
2167 [MSG], [object()])
2168 self.assertRaises(TypeError, self.sendmsgToServer,
2169 [MSG], [(object(), 0, b"data")])
2170 self.assertRaises(TypeError, self.sendmsgToServer,
2171 [MSG], [(0, object(), b"data")])
2172 self.assertRaises(TypeError, self.sendmsgToServer,
2173 [MSG], [(0, 0, object())])
2174 self.assertRaises(TypeError, self.sendmsgToServer,
2175 [MSG], [(0, 0)])
2176 self.assertRaises(TypeError, self.sendmsgToServer,
2177 [MSG], [(0, 0, b"data", 42)])
2178 self.sendToServer(b"done")
2179
2180 @requireAttrs(socket, "CMSG_SPACE")
2181 def testSendmsgBadMultiCmsg(self):
2182 # Check that invalid ancillary data items are rejected when
2183 # more than one item is present.
2184 self.assertEqual(self.serv_sock.recv(1000), b"done")
2185
2186 @testSendmsgBadMultiCmsg.client_skip
2187 def _testSendmsgBadMultiCmsg(self):
2188 self.assertRaises(TypeError, self.sendmsgToServer,
2189 [MSG], [0, 0, b""])
2190 self.assertRaises(TypeError, self.sendmsgToServer,
2191 [MSG], [(0, 0, b""), object()])
2192 self.sendToServer(b"done")
2193
2194 def testSendmsgExcessCmsgReject(self):
2195 # Check that sendmsg() rejects excess ancillary data items
2196 # when the number that can be sent is limited.
2197 self.assertEqual(self.serv_sock.recv(1000), b"done")
2198
2199 def _testSendmsgExcessCmsgReject(self):
2200 if not hasattr(socket, "CMSG_SPACE"):
2201 # Can only send one item
Andrew Svetlov0832af62012-12-18 23:10:48 +02002202 with self.assertRaises(OSError) as cm:
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002203 self.sendmsgToServer([MSG], [(0, 0, b""), (0, 0, b"")])
2204 self.assertIsNone(cm.exception.errno)
2205 self.sendToServer(b"done")
2206
2207 def testSendmsgAfterClose(self):
2208 # Check that sendmsg() fails on a closed socket.
2209 pass
2210
2211 def _testSendmsgAfterClose(self):
2212 self.cli_sock.close()
Andrew Svetlov0832af62012-12-18 23:10:48 +02002213 self.assertRaises(OSError, self.sendmsgToServer, [MSG])
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002214
2215
2216class SendmsgStreamTests(SendmsgTests):
2217 # Tests for sendmsg() which require a stream socket and do not
2218 # involve recvmsg() or recvmsg_into().
2219
2220 def testSendmsgExplicitNoneAddr(self):
2221 # Check that peer address can be specified as None.
2222 self.assertEqual(self.serv_sock.recv(len(MSG)), MSG)
2223
2224 def _testSendmsgExplicitNoneAddr(self):
2225 self.assertEqual(self.sendmsgToServer([MSG], [], 0, None), len(MSG))
2226
2227 def testSendmsgTimeout(self):
2228 # Check that timeout works with sendmsg().
2229 self.assertEqual(self.serv_sock.recv(512), b"a"*512)
2230 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
2231
2232 def _testSendmsgTimeout(self):
2233 try:
2234 self.cli_sock.settimeout(0.03)
2235 with self.assertRaises(socket.timeout):
2236 while True:
2237 self.sendmsgToServer([b"a"*512])
2238 finally:
2239 self.misc_event.set()
2240
2241 # XXX: would be nice to have more tests for sendmsg flags argument.
2242
2243 # Linux supports MSG_DONTWAIT when sending, but in general, it
2244 # only works when receiving. Could add other platforms if they
2245 # support it too.
Serhiy Storchakaabde2c12014-11-19 13:21:13 +02002246 @skipWithClientIf(sys.platform not in {"linux"},
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002247 "MSG_DONTWAIT not known to work on this platform when "
2248 "sending")
2249 def testSendmsgDontWait(self):
2250 # Check that MSG_DONTWAIT in flags causes non-blocking behaviour.
2251 self.assertEqual(self.serv_sock.recv(512), b"a"*512)
2252 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
2253
2254 @testSendmsgDontWait.client_skip
2255 def _testSendmsgDontWait(self):
2256 try:
Andrew Svetlov0832af62012-12-18 23:10:48 +02002257 with self.assertRaises(OSError) as cm:
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002258 while True:
2259 self.sendmsgToServer([b"a"*512], [], socket.MSG_DONTWAIT)
2260 self.assertIn(cm.exception.errno,
2261 (errno.EAGAIN, errno.EWOULDBLOCK))
2262 finally:
2263 self.misc_event.set()
2264
2265
2266class SendmsgConnectionlessTests(SendmsgTests):
2267 # Tests for sendmsg() which require a connectionless-mode
2268 # (e.g. datagram) socket, and do not involve recvmsg() or
2269 # recvmsg_into().
2270
2271 def testSendmsgNoDestAddr(self):
2272 # Check that sendmsg() fails when no destination address is
2273 # given for unconnected socket.
2274 pass
2275
2276 def _testSendmsgNoDestAddr(self):
Andrew Svetlov0832af62012-12-18 23:10:48 +02002277 self.assertRaises(OSError, self.cli_sock.sendmsg,
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002278 [MSG])
Andrew Svetlov0832af62012-12-18 23:10:48 +02002279 self.assertRaises(OSError, self.cli_sock.sendmsg,
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002280 [MSG], [], 0, None)
2281
2282
2283class RecvmsgGenericTests(SendrecvmsgBase):
2284 # Tests for recvmsg() which can also be emulated using
2285 # recvmsg_into(), and can use any socket type.
2286
2287 def testRecvmsg(self):
2288 # Receive a simple message with recvmsg[_into]().
2289 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, len(MSG))
2290 self.assertEqual(msg, MSG)
2291 self.checkRecvmsgAddress(addr, self.cli_addr)
2292 self.assertEqual(ancdata, [])
2293 self.checkFlags(flags, eor=True)
2294
2295 def _testRecvmsg(self):
2296 self.sendToServer(MSG)
2297
2298 def testRecvmsgExplicitDefaults(self):
2299 # Test recvmsg[_into]() with default arguments provided explicitly.
2300 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
2301 len(MSG), 0, 0)
2302 self.assertEqual(msg, MSG)
2303 self.checkRecvmsgAddress(addr, self.cli_addr)
2304 self.assertEqual(ancdata, [])
2305 self.checkFlags(flags, eor=True)
2306
2307 def _testRecvmsgExplicitDefaults(self):
2308 self.sendToServer(MSG)
2309
2310 def testRecvmsgShorter(self):
2311 # Receive a message smaller than buffer.
2312 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
2313 len(MSG) + 42)
2314 self.assertEqual(msg, MSG)
2315 self.checkRecvmsgAddress(addr, self.cli_addr)
2316 self.assertEqual(ancdata, [])
2317 self.checkFlags(flags, eor=True)
2318
2319 def _testRecvmsgShorter(self):
2320 self.sendToServer(MSG)
2321
Charles-François Natali8619cd72011-10-03 19:43:15 +02002322 # FreeBSD < 8 doesn't always set the MSG_TRUNC flag when a truncated
2323 # datagram is received (issue #13001).
2324 @support.requires_freebsd_version(8)
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002325 def testRecvmsgTrunc(self):
2326 # Receive part of message, check for truncation indicators.
2327 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
2328 len(MSG) - 3)
2329 self.assertEqual(msg, MSG[:-3])
2330 self.checkRecvmsgAddress(addr, self.cli_addr)
2331 self.assertEqual(ancdata, [])
2332 self.checkFlags(flags, eor=False)
2333
Charles-François Natali8619cd72011-10-03 19:43:15 +02002334 @support.requires_freebsd_version(8)
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002335 def _testRecvmsgTrunc(self):
2336 self.sendToServer(MSG)
2337
2338 def testRecvmsgShortAncillaryBuf(self):
2339 # Test ancillary data buffer too small to hold any ancillary data.
2340 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
2341 len(MSG), 1)
2342 self.assertEqual(msg, MSG)
2343 self.checkRecvmsgAddress(addr, self.cli_addr)
2344 self.assertEqual(ancdata, [])
2345 self.checkFlags(flags, eor=True)
2346
2347 def _testRecvmsgShortAncillaryBuf(self):
2348 self.sendToServer(MSG)
2349
2350 def testRecvmsgLongAncillaryBuf(self):
2351 # Test large ancillary data buffer.
2352 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
2353 len(MSG), 10240)
2354 self.assertEqual(msg, MSG)
2355 self.checkRecvmsgAddress(addr, self.cli_addr)
2356 self.assertEqual(ancdata, [])
2357 self.checkFlags(flags, eor=True)
2358
2359 def _testRecvmsgLongAncillaryBuf(self):
2360 self.sendToServer(MSG)
2361
2362 def testRecvmsgAfterClose(self):
2363 # Check that recvmsg[_into]() fails on a closed socket.
2364 self.serv_sock.close()
Andrew Svetlov0832af62012-12-18 23:10:48 +02002365 self.assertRaises(OSError, self.doRecvmsg, self.serv_sock, 1024)
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002366
2367 def _testRecvmsgAfterClose(self):
2368 pass
2369
2370 def testRecvmsgTimeout(self):
2371 # Check that timeout works.
2372 try:
2373 self.serv_sock.settimeout(0.03)
2374 self.assertRaises(socket.timeout,
2375 self.doRecvmsg, self.serv_sock, len(MSG))
2376 finally:
2377 self.misc_event.set()
2378
2379 def _testRecvmsgTimeout(self):
2380 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
2381
2382 @requireAttrs(socket, "MSG_PEEK")
2383 def testRecvmsgPeek(self):
2384 # Check that MSG_PEEK in flags enables examination of pending
2385 # data without consuming it.
2386
2387 # Receive part of data with MSG_PEEK.
2388 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
2389 len(MSG) - 3, 0,
2390 socket.MSG_PEEK)
2391 self.assertEqual(msg, MSG[:-3])
2392 self.checkRecvmsgAddress(addr, self.cli_addr)
2393 self.assertEqual(ancdata, [])
2394 # Ignoring MSG_TRUNC here (so this test is the same for stream
2395 # and datagram sockets). Some wording in POSIX seems to
2396 # suggest that it needn't be set when peeking, but that may
2397 # just be a slip.
2398 self.checkFlags(flags, eor=False,
2399 ignore=getattr(socket, "MSG_TRUNC", 0))
2400
2401 # Receive all data with MSG_PEEK.
2402 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
2403 len(MSG), 0,
2404 socket.MSG_PEEK)
2405 self.assertEqual(msg, MSG)
2406 self.checkRecvmsgAddress(addr, self.cli_addr)
2407 self.assertEqual(ancdata, [])
2408 self.checkFlags(flags, eor=True)
2409
2410 # Check that the same data can still be received normally.
2411 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, len(MSG))
2412 self.assertEqual(msg, MSG)
2413 self.checkRecvmsgAddress(addr, self.cli_addr)
2414 self.assertEqual(ancdata, [])
2415 self.checkFlags(flags, eor=True)
2416
2417 @testRecvmsgPeek.client_skip
2418 def _testRecvmsgPeek(self):
2419 self.sendToServer(MSG)
2420
2421 @requireAttrs(socket.socket, "sendmsg")
2422 def testRecvmsgFromSendmsg(self):
2423 # Test receiving with recvmsg[_into]() when message is sent
2424 # using sendmsg().
2425 self.serv_sock.settimeout(self.fail_timeout)
2426 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, len(MSG))
2427 self.assertEqual(msg, MSG)
2428 self.checkRecvmsgAddress(addr, self.cli_addr)
2429 self.assertEqual(ancdata, [])
2430 self.checkFlags(flags, eor=True)
2431
2432 @testRecvmsgFromSendmsg.client_skip
2433 def _testRecvmsgFromSendmsg(self):
2434 self.assertEqual(self.sendmsgToServer([MSG[:3], MSG[3:]]), len(MSG))
2435
2436
2437class RecvmsgGenericStreamTests(RecvmsgGenericTests):
2438 # Tests which require a stream socket and can use either recvmsg()
2439 # or recvmsg_into().
2440
2441 def testRecvmsgEOF(self):
2442 # Receive end-of-stream indicator (b"", peer socket closed).
2443 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, 1024)
2444 self.assertEqual(msg, b"")
2445 self.checkRecvmsgAddress(addr, self.cli_addr)
2446 self.assertEqual(ancdata, [])
2447 self.checkFlags(flags, eor=None) # Might not have end-of-record marker
2448
2449 def _testRecvmsgEOF(self):
2450 self.cli_sock.close()
2451
2452 def testRecvmsgOverflow(self):
2453 # Receive a message in more than one chunk.
2454 seg1, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
2455 len(MSG) - 3)
2456 self.checkRecvmsgAddress(addr, self.cli_addr)
2457 self.assertEqual(ancdata, [])
2458 self.checkFlags(flags, eor=False)
2459
2460 seg2, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, 1024)
2461 self.checkRecvmsgAddress(addr, self.cli_addr)
2462 self.assertEqual(ancdata, [])
2463 self.checkFlags(flags, eor=True)
2464
2465 msg = seg1 + seg2
2466 self.assertEqual(msg, MSG)
2467
2468 def _testRecvmsgOverflow(self):
2469 self.sendToServer(MSG)
2470
2471
2472class RecvmsgTests(RecvmsgGenericTests):
2473 # Tests for recvmsg() which can use any socket type.
2474
2475 def testRecvmsgBadArgs(self):
2476 # Check that recvmsg() rejects invalid arguments.
2477 self.assertRaises(TypeError, self.serv_sock.recvmsg)
2478 self.assertRaises(ValueError, self.serv_sock.recvmsg,
2479 -1, 0, 0)
2480 self.assertRaises(ValueError, self.serv_sock.recvmsg,
2481 len(MSG), -1, 0)
2482 self.assertRaises(TypeError, self.serv_sock.recvmsg,
2483 [bytearray(10)], 0, 0)
2484 self.assertRaises(TypeError, self.serv_sock.recvmsg,
2485 object(), 0, 0)
2486 self.assertRaises(TypeError, self.serv_sock.recvmsg,
2487 len(MSG), object(), 0)
2488 self.assertRaises(TypeError, self.serv_sock.recvmsg,
2489 len(MSG), 0, object())
2490
2491 msg, ancdata, flags, addr = self.serv_sock.recvmsg(len(MSG), 0, 0)
2492 self.assertEqual(msg, MSG)
2493 self.checkRecvmsgAddress(addr, self.cli_addr)
2494 self.assertEqual(ancdata, [])
2495 self.checkFlags(flags, eor=True)
2496
2497 def _testRecvmsgBadArgs(self):
2498 self.sendToServer(MSG)
2499
2500
2501class RecvmsgIntoTests(RecvmsgIntoMixin, RecvmsgGenericTests):
2502 # Tests for recvmsg_into() which can use any socket type.
2503
2504 def testRecvmsgIntoBadArgs(self):
2505 # Check that recvmsg_into() rejects invalid arguments.
2506 buf = bytearray(len(MSG))
2507 self.assertRaises(TypeError, self.serv_sock.recvmsg_into)
2508 self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
2509 len(MSG), 0, 0)
2510 self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
2511 buf, 0, 0)
2512 self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
2513 [object()], 0, 0)
2514 self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
2515 [b"I'm not writable"], 0, 0)
2516 self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
2517 [buf, object()], 0, 0)
2518 self.assertRaises(ValueError, self.serv_sock.recvmsg_into,
2519 [buf], -1, 0)
2520 self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
2521 [buf], object(), 0)
2522 self.assertRaises(TypeError, self.serv_sock.recvmsg_into,
2523 [buf], 0, object())
2524
2525 nbytes, ancdata, flags, addr = self.serv_sock.recvmsg_into([buf], 0, 0)
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 _testRecvmsgIntoBadArgs(self):
2533 self.sendToServer(MSG)
2534
2535 def testRecvmsgIntoGenerator(self):
2536 # Receive into buffer obtained from a generator (not a sequence).
2537 buf = bytearray(len(MSG))
2538 nbytes, ancdata, flags, addr = self.serv_sock.recvmsg_into(
2539 (o for o in [buf]))
2540 self.assertEqual(nbytes, len(MSG))
2541 self.assertEqual(buf, bytearray(MSG))
2542 self.checkRecvmsgAddress(addr, self.cli_addr)
2543 self.assertEqual(ancdata, [])
2544 self.checkFlags(flags, eor=True)
2545
2546 def _testRecvmsgIntoGenerator(self):
2547 self.sendToServer(MSG)
2548
2549 def testRecvmsgIntoArray(self):
2550 # Receive into an array rather than the usual bytearray.
2551 buf = array.array("B", [0] * len(MSG))
2552 nbytes, ancdata, flags, addr = self.serv_sock.recvmsg_into([buf])
2553 self.assertEqual(nbytes, len(MSG))
Nadeem Vawda3d1706f2011-08-22 09:46:56 +02002554 self.assertEqual(buf.tobytes(), MSG)
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002555 self.checkRecvmsgAddress(addr, self.cli_addr)
2556 self.assertEqual(ancdata, [])
2557 self.checkFlags(flags, eor=True)
2558
2559 def _testRecvmsgIntoArray(self):
2560 self.sendToServer(MSG)
2561
2562 def testRecvmsgIntoScatter(self):
2563 # Receive into multiple buffers (scatter write).
2564 b1 = bytearray(b"----")
2565 b2 = bytearray(b"0123456789")
2566 b3 = bytearray(b"--------------")
2567 nbytes, ancdata, flags, addr = self.serv_sock.recvmsg_into(
2568 [b1, memoryview(b2)[2:9], b3])
2569 self.assertEqual(nbytes, len(b"Mary had a little lamb"))
2570 self.assertEqual(b1, bytearray(b"Mary"))
2571 self.assertEqual(b2, bytearray(b"01 had a 9"))
2572 self.assertEqual(b3, bytearray(b"little lamb---"))
2573 self.checkRecvmsgAddress(addr, self.cli_addr)
2574 self.assertEqual(ancdata, [])
2575 self.checkFlags(flags, eor=True)
2576
2577 def _testRecvmsgIntoScatter(self):
2578 self.sendToServer(b"Mary had a little lamb")
2579
2580
2581class CmsgMacroTests(unittest.TestCase):
2582 # Test the functions CMSG_LEN() and CMSG_SPACE(). Tests
2583 # assumptions used by sendmsg() and recvmsg[_into](), which share
2584 # code with these functions.
2585
2586 # Match the definition in socketmodule.c
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02002587 try:
2588 import _testcapi
2589 except ImportError:
2590 socklen_t_limit = 0x7fffffff
2591 else:
2592 socklen_t_limit = min(0x7fffffff, _testcapi.INT_MAX)
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002593
2594 @requireAttrs(socket, "CMSG_LEN")
2595 def testCMSG_LEN(self):
2596 # Test CMSG_LEN() with various valid and invalid values,
2597 # checking the assumptions used by recvmsg() and sendmsg().
2598 toobig = self.socklen_t_limit - socket.CMSG_LEN(0) + 1
2599 values = list(range(257)) + list(range(toobig - 257, toobig))
2600
2601 # struct cmsghdr has at least three members, two of which are ints
2602 self.assertGreater(socket.CMSG_LEN(0), array.array("i").itemsize * 2)
2603 for n in values:
2604 ret = socket.CMSG_LEN(n)
2605 # This is how recvmsg() calculates the data size
2606 self.assertEqual(ret - socket.CMSG_LEN(0), n)
2607 self.assertLessEqual(ret, self.socklen_t_limit)
2608
2609 self.assertRaises(OverflowError, socket.CMSG_LEN, -1)
2610 # sendmsg() shares code with these functions, and requires
2611 # that it reject values over the limit.
2612 self.assertRaises(OverflowError, socket.CMSG_LEN, toobig)
2613 self.assertRaises(OverflowError, socket.CMSG_LEN, sys.maxsize)
2614
2615 @requireAttrs(socket, "CMSG_SPACE")
2616 def testCMSG_SPACE(self):
2617 # Test CMSG_SPACE() with various valid and invalid values,
2618 # checking the assumptions used by sendmsg().
2619 toobig = self.socklen_t_limit - socket.CMSG_SPACE(1) + 1
2620 values = list(range(257)) + list(range(toobig - 257, toobig))
2621
2622 last = socket.CMSG_SPACE(0)
2623 # struct cmsghdr has at least three members, two of which are ints
2624 self.assertGreater(last, array.array("i").itemsize * 2)
2625 for n in values:
2626 ret = socket.CMSG_SPACE(n)
2627 self.assertGreaterEqual(ret, last)
2628 self.assertGreaterEqual(ret, socket.CMSG_LEN(n))
2629 self.assertGreaterEqual(ret, n + socket.CMSG_LEN(0))
2630 self.assertLessEqual(ret, self.socklen_t_limit)
2631 last = ret
2632
2633 self.assertRaises(OverflowError, socket.CMSG_SPACE, -1)
2634 # sendmsg() shares code with these functions, and requires
2635 # that it reject values over the limit.
2636 self.assertRaises(OverflowError, socket.CMSG_SPACE, toobig)
2637 self.assertRaises(OverflowError, socket.CMSG_SPACE, sys.maxsize)
2638
2639
2640class SCMRightsTest(SendrecvmsgServerTimeoutBase):
2641 # Tests for file descriptor passing on Unix-domain sockets.
2642
2643 # Invalid file descriptor value that's unlikely to evaluate to a
2644 # real FD even if one of its bytes is replaced with a different
2645 # value (which shouldn't actually happen).
2646 badfd = -0x5555
2647
2648 def newFDs(self, n):
2649 # Return a list of n file descriptors for newly-created files
2650 # containing their list indices as ASCII numbers.
2651 fds = []
2652 for i in range(n):
2653 fd, path = tempfile.mkstemp()
2654 self.addCleanup(os.unlink, path)
2655 self.addCleanup(os.close, fd)
2656 os.write(fd, str(i).encode())
2657 fds.append(fd)
2658 return fds
2659
2660 def checkFDs(self, fds):
2661 # Check that the file descriptors in the given list contain
2662 # their correct list indices as ASCII numbers.
2663 for n, fd in enumerate(fds):
2664 os.lseek(fd, 0, os.SEEK_SET)
2665 self.assertEqual(os.read(fd, 1024), str(n).encode())
2666
2667 def registerRecvmsgResult(self, result):
2668 self.addCleanup(self.closeRecvmsgFDs, result)
2669
2670 def closeRecvmsgFDs(self, recvmsg_result):
2671 # Close all file descriptors specified in the ancillary data
2672 # of the given return value from recvmsg() or recvmsg_into().
2673 for cmsg_level, cmsg_type, cmsg_data in recvmsg_result[1]:
2674 if (cmsg_level == socket.SOL_SOCKET and
2675 cmsg_type == socket.SCM_RIGHTS):
2676 fds = array.array("i")
Nadeem Vawda3d1706f2011-08-22 09:46:56 +02002677 fds.frombytes(cmsg_data[:
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002678 len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
2679 for fd in fds:
2680 os.close(fd)
2681
2682 def createAndSendFDs(self, n):
2683 # Send n new file descriptors created by newFDs() to the
2684 # server, with the constant MSG as the non-ancillary data.
2685 self.assertEqual(
2686 self.sendmsgToServer([MSG],
2687 [(socket.SOL_SOCKET,
2688 socket.SCM_RIGHTS,
2689 array.array("i", self.newFDs(n)))]),
2690 len(MSG))
2691
2692 def checkRecvmsgFDs(self, numfds, result, maxcmsgs=1, ignoreflags=0):
2693 # Check that constant MSG was received with numfds file
2694 # descriptors in a maximum of maxcmsgs control messages (which
2695 # must contain only complete integers). By default, check
2696 # that MSG_CTRUNC is unset, but ignore any flags in
2697 # ignoreflags.
2698 msg, ancdata, flags, addr = result
2699 self.assertEqual(msg, MSG)
2700 self.checkRecvmsgAddress(addr, self.cli_addr)
2701 self.checkFlags(flags, eor=True, checkunset=socket.MSG_CTRUNC,
2702 ignore=ignoreflags)
2703
2704 self.assertIsInstance(ancdata, list)
2705 self.assertLessEqual(len(ancdata), maxcmsgs)
2706 fds = array.array("i")
2707 for item in ancdata:
2708 self.assertIsInstance(item, tuple)
2709 cmsg_level, cmsg_type, cmsg_data = item
2710 self.assertEqual(cmsg_level, socket.SOL_SOCKET)
2711 self.assertEqual(cmsg_type, socket.SCM_RIGHTS)
2712 self.assertIsInstance(cmsg_data, bytes)
2713 self.assertEqual(len(cmsg_data) % SIZEOF_INT, 0)
Nadeem Vawda3d1706f2011-08-22 09:46:56 +02002714 fds.frombytes(cmsg_data)
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002715
2716 self.assertEqual(len(fds), numfds)
2717 self.checkFDs(fds)
2718
2719 def testFDPassSimple(self):
2720 # Pass a single FD (array read from bytes object).
2721 self.checkRecvmsgFDs(1, self.doRecvmsg(self.serv_sock,
2722 len(MSG), 10240))
2723
2724 def _testFDPassSimple(self):
2725 self.assertEqual(
2726 self.sendmsgToServer(
2727 [MSG],
2728 [(socket.SOL_SOCKET,
2729 socket.SCM_RIGHTS,
Nadeem Vawda3d1706f2011-08-22 09:46:56 +02002730 array.array("i", self.newFDs(1)).tobytes())]),
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002731 len(MSG))
2732
2733 def testMultipleFDPass(self):
2734 # Pass multiple FDs in a single array.
2735 self.checkRecvmsgFDs(4, self.doRecvmsg(self.serv_sock,
2736 len(MSG), 10240))
2737
2738 def _testMultipleFDPass(self):
2739 self.createAndSendFDs(4)
2740
2741 @requireAttrs(socket, "CMSG_SPACE")
2742 def testFDPassCMSG_SPACE(self):
2743 # Test using CMSG_SPACE() to calculate ancillary buffer size.
2744 self.checkRecvmsgFDs(
2745 4, self.doRecvmsg(self.serv_sock, len(MSG),
2746 socket.CMSG_SPACE(4 * SIZEOF_INT)))
2747
2748 @testFDPassCMSG_SPACE.client_skip
2749 def _testFDPassCMSG_SPACE(self):
2750 self.createAndSendFDs(4)
2751
2752 def testFDPassCMSG_LEN(self):
2753 # Test using CMSG_LEN() to calculate ancillary buffer size.
2754 self.checkRecvmsgFDs(1,
2755 self.doRecvmsg(self.serv_sock, len(MSG),
2756 socket.CMSG_LEN(4 * SIZEOF_INT)),
2757 # RFC 3542 says implementations may set
2758 # MSG_CTRUNC if there isn't enough space
2759 # for trailing padding.
2760 ignoreflags=socket.MSG_CTRUNC)
2761
2762 def _testFDPassCMSG_LEN(self):
2763 self.createAndSendFDs(1)
2764
Charles-Francois Natalid66b10e2013-05-20 19:08:19 +02002765 @unittest.skipIf(sys.platform == "darwin", "skipping, see issue #12958")
Robert Collins43cbbe22015-08-03 10:36:04 +12002766 @unittest.skipIf(sys.platform.startswith("aix"), "skipping, see issue #22397")
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002767 @requireAttrs(socket, "CMSG_SPACE")
2768 def testFDPassSeparate(self):
2769 # Pass two FDs in two separate arrays. Arrays may be combined
2770 # into a single control message by the OS.
2771 self.checkRecvmsgFDs(2,
2772 self.doRecvmsg(self.serv_sock, len(MSG), 10240),
2773 maxcmsgs=2)
2774
2775 @testFDPassSeparate.client_skip
Charles-Francois Natalid66b10e2013-05-20 19:08:19 +02002776 @unittest.skipIf(sys.platform == "darwin", "skipping, see issue #12958")
Robert Collins43cbbe22015-08-03 10:36:04 +12002777 @unittest.skipIf(sys.platform.startswith("aix"), "skipping, see issue #22397")
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002778 def _testFDPassSeparate(self):
2779 fd0, fd1 = self.newFDs(2)
2780 self.assertEqual(
2781 self.sendmsgToServer([MSG], [(socket.SOL_SOCKET,
2782 socket.SCM_RIGHTS,
2783 array.array("i", [fd0])),
2784 (socket.SOL_SOCKET,
2785 socket.SCM_RIGHTS,
2786 array.array("i", [fd1]))]),
2787 len(MSG))
2788
Charles-Francois Natalid66b10e2013-05-20 19:08:19 +02002789 @unittest.skipIf(sys.platform == "darwin", "skipping, see issue #12958")
Robert Collins43cbbe22015-08-03 10:36:04 +12002790 @unittest.skipIf(sys.platform.startswith("aix"), "skipping, see issue #22397")
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002791 @requireAttrs(socket, "CMSG_SPACE")
2792 def testFDPassSeparateMinSpace(self):
2793 # Pass two FDs in two separate arrays, receiving them into the
2794 # minimum space for two arrays.
2795 self.checkRecvmsgFDs(2,
2796 self.doRecvmsg(self.serv_sock, len(MSG),
2797 socket.CMSG_SPACE(SIZEOF_INT) +
2798 socket.CMSG_LEN(SIZEOF_INT)),
2799 maxcmsgs=2, ignoreflags=socket.MSG_CTRUNC)
2800
2801 @testFDPassSeparateMinSpace.client_skip
Charles-Francois Natalid66b10e2013-05-20 19:08:19 +02002802 @unittest.skipIf(sys.platform == "darwin", "skipping, see issue #12958")
Robert Collins43cbbe22015-08-03 10:36:04 +12002803 @unittest.skipIf(sys.platform.startswith("aix"), "skipping, see issue #22397")
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002804 def _testFDPassSeparateMinSpace(self):
2805 fd0, fd1 = self.newFDs(2)
2806 self.assertEqual(
2807 self.sendmsgToServer([MSG], [(socket.SOL_SOCKET,
2808 socket.SCM_RIGHTS,
2809 array.array("i", [fd0])),
2810 (socket.SOL_SOCKET,
2811 socket.SCM_RIGHTS,
2812 array.array("i", [fd1]))]),
2813 len(MSG))
2814
2815 def sendAncillaryIfPossible(self, msg, ancdata):
2816 # Try to send msg and ancdata to server, but if the system
2817 # call fails, just send msg with no ancillary data.
2818 try:
2819 nbytes = self.sendmsgToServer([msg], ancdata)
Andrew Svetlov0832af62012-12-18 23:10:48 +02002820 except OSError as e:
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002821 # Check that it was the system call that failed
2822 self.assertIsInstance(e.errno, int)
2823 nbytes = self.sendmsgToServer([msg])
2824 self.assertEqual(nbytes, len(msg))
2825
2826 def testFDPassEmpty(self):
2827 # Try to pass an empty FD array. Can receive either no array
2828 # or an empty array.
2829 self.checkRecvmsgFDs(0, self.doRecvmsg(self.serv_sock,
2830 len(MSG), 10240),
2831 ignoreflags=socket.MSG_CTRUNC)
2832
2833 def _testFDPassEmpty(self):
2834 self.sendAncillaryIfPossible(MSG, [(socket.SOL_SOCKET,
2835 socket.SCM_RIGHTS,
2836 b"")])
2837
2838 def testFDPassPartialInt(self):
2839 # Try to pass a truncated FD array.
2840 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
2841 len(MSG), 10240)
2842 self.assertEqual(msg, MSG)
2843 self.checkRecvmsgAddress(addr, self.cli_addr)
2844 self.checkFlags(flags, eor=True, ignore=socket.MSG_CTRUNC)
2845 self.assertLessEqual(len(ancdata), 1)
2846 for cmsg_level, cmsg_type, cmsg_data in ancdata:
2847 self.assertEqual(cmsg_level, socket.SOL_SOCKET)
2848 self.assertEqual(cmsg_type, socket.SCM_RIGHTS)
2849 self.assertLess(len(cmsg_data), SIZEOF_INT)
2850
2851 def _testFDPassPartialInt(self):
2852 self.sendAncillaryIfPossible(
2853 MSG,
2854 [(socket.SOL_SOCKET,
2855 socket.SCM_RIGHTS,
Nadeem Vawda3d1706f2011-08-22 09:46:56 +02002856 array.array("i", [self.badfd]).tobytes()[:-1])])
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002857
2858 @requireAttrs(socket, "CMSG_SPACE")
2859 def testFDPassPartialIntInMiddle(self):
2860 # Try to pass two FD arrays, the first of which is truncated.
2861 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
2862 len(MSG), 10240)
2863 self.assertEqual(msg, MSG)
2864 self.checkRecvmsgAddress(addr, self.cli_addr)
2865 self.checkFlags(flags, eor=True, ignore=socket.MSG_CTRUNC)
2866 self.assertLessEqual(len(ancdata), 2)
2867 fds = array.array("i")
2868 # Arrays may have been combined in a single control message
2869 for cmsg_level, cmsg_type, cmsg_data in ancdata:
2870 self.assertEqual(cmsg_level, socket.SOL_SOCKET)
2871 self.assertEqual(cmsg_type, socket.SCM_RIGHTS)
Nadeem Vawda3d1706f2011-08-22 09:46:56 +02002872 fds.frombytes(cmsg_data[:
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002873 len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
2874 self.assertLessEqual(len(fds), 2)
2875 self.checkFDs(fds)
2876
2877 @testFDPassPartialIntInMiddle.client_skip
2878 def _testFDPassPartialIntInMiddle(self):
2879 fd0, fd1 = self.newFDs(2)
2880 self.sendAncillaryIfPossible(
2881 MSG,
2882 [(socket.SOL_SOCKET,
2883 socket.SCM_RIGHTS,
Nadeem Vawda3d1706f2011-08-22 09:46:56 +02002884 array.array("i", [fd0, self.badfd]).tobytes()[:-1]),
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002885 (socket.SOL_SOCKET,
2886 socket.SCM_RIGHTS,
2887 array.array("i", [fd1]))])
2888
2889 def checkTruncatedHeader(self, result, ignoreflags=0):
2890 # Check that no ancillary data items are returned when data is
2891 # truncated inside the cmsghdr structure.
2892 msg, ancdata, flags, addr = result
2893 self.assertEqual(msg, MSG)
2894 self.checkRecvmsgAddress(addr, self.cli_addr)
2895 self.assertEqual(ancdata, [])
2896 self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC,
2897 ignore=ignoreflags)
2898
2899 def testCmsgTruncNoBufSize(self):
2900 # Check that no ancillary data is received when no buffer size
2901 # is specified.
2902 self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG)),
2903 # BSD seems to set MSG_CTRUNC only
2904 # if an item has been partially
2905 # received.
2906 ignoreflags=socket.MSG_CTRUNC)
2907
2908 def _testCmsgTruncNoBufSize(self):
2909 self.createAndSendFDs(1)
2910
2911 def testCmsgTrunc0(self):
2912 # Check that no ancillary data is received when buffer size is 0.
2913 self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG), 0),
2914 ignoreflags=socket.MSG_CTRUNC)
2915
2916 def _testCmsgTrunc0(self):
2917 self.createAndSendFDs(1)
2918
2919 # Check that no ancillary data is returned for various non-zero
2920 # (but still too small) buffer sizes.
2921
2922 def testCmsgTrunc1(self):
2923 self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG), 1))
2924
2925 def _testCmsgTrunc1(self):
2926 self.createAndSendFDs(1)
2927
2928 def testCmsgTrunc2Int(self):
2929 # The cmsghdr structure has at least three members, two of
2930 # which are ints, so we still shouldn't see any ancillary
2931 # data.
2932 self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG),
2933 SIZEOF_INT * 2))
2934
2935 def _testCmsgTrunc2Int(self):
2936 self.createAndSendFDs(1)
2937
2938 def testCmsgTruncLen0Minus1(self):
2939 self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG),
2940 socket.CMSG_LEN(0) - 1))
2941
2942 def _testCmsgTruncLen0Minus1(self):
2943 self.createAndSendFDs(1)
2944
2945 # The following tests try to truncate the control message in the
2946 # middle of the FD array.
2947
2948 def checkTruncatedArray(self, ancbuf, maxdata, mindata=0):
2949 # Check that file descriptor data is truncated to between
2950 # mindata and maxdata bytes when received with buffer size
2951 # ancbuf, and that any complete file descriptor numbers are
2952 # valid.
2953 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
2954 len(MSG), ancbuf)
2955 self.assertEqual(msg, MSG)
2956 self.checkRecvmsgAddress(addr, self.cli_addr)
2957 self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC)
2958
2959 if mindata == 0 and ancdata == []:
2960 return
2961 self.assertEqual(len(ancdata), 1)
2962 cmsg_level, cmsg_type, cmsg_data = ancdata[0]
2963 self.assertEqual(cmsg_level, socket.SOL_SOCKET)
2964 self.assertEqual(cmsg_type, socket.SCM_RIGHTS)
2965 self.assertGreaterEqual(len(cmsg_data), mindata)
2966 self.assertLessEqual(len(cmsg_data), maxdata)
2967 fds = array.array("i")
Nadeem Vawda3d1706f2011-08-22 09:46:56 +02002968 fds.frombytes(cmsg_data[:
Nick Coghlan96fe56a2011-08-22 11:55:57 +10002969 len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
2970 self.checkFDs(fds)
2971
2972 def testCmsgTruncLen0(self):
2973 self.checkTruncatedArray(ancbuf=socket.CMSG_LEN(0), maxdata=0)
2974
2975 def _testCmsgTruncLen0(self):
2976 self.createAndSendFDs(1)
2977
2978 def testCmsgTruncLen0Plus1(self):
2979 self.checkTruncatedArray(ancbuf=socket.CMSG_LEN(0) + 1, maxdata=1)
2980
2981 def _testCmsgTruncLen0Plus1(self):
2982 self.createAndSendFDs(2)
2983
2984 def testCmsgTruncLen1(self):
2985 self.checkTruncatedArray(ancbuf=socket.CMSG_LEN(SIZEOF_INT),
2986 maxdata=SIZEOF_INT)
2987
2988 def _testCmsgTruncLen1(self):
2989 self.createAndSendFDs(2)
2990
2991 def testCmsgTruncLen2Minus1(self):
2992 self.checkTruncatedArray(ancbuf=socket.CMSG_LEN(2 * SIZEOF_INT) - 1,
2993 maxdata=(2 * SIZEOF_INT) - 1)
2994
2995 def _testCmsgTruncLen2Minus1(self):
2996 self.createAndSendFDs(2)
2997
2998
2999class RFC3542AncillaryTest(SendrecvmsgServerTimeoutBase):
3000 # Test sendmsg() and recvmsg[_into]() using the ancillary data
3001 # features of the RFC 3542 Advanced Sockets API for IPv6.
3002 # Currently we can only handle certain data items (e.g. traffic
3003 # class, hop limit, MTU discovery and fragmentation settings)
3004 # without resorting to unportable means such as the struct module,
3005 # but the tests here are aimed at testing the ancillary data
3006 # handling in sendmsg() and recvmsg() rather than the IPv6 API
3007 # itself.
3008
3009 # Test value to use when setting hop limit of packet
3010 hop_limit = 2
3011
3012 # Test value to use when setting traffic class of packet.
3013 # -1 means "use kernel default".
3014 traffic_class = -1
3015
3016 def ancillaryMapping(self, ancdata):
3017 # Given ancillary data list ancdata, return a mapping from
3018 # pairs (cmsg_level, cmsg_type) to corresponding cmsg_data.
3019 # Check that no (level, type) pair appears more than once.
3020 d = {}
3021 for cmsg_level, cmsg_type, cmsg_data in ancdata:
3022 self.assertNotIn((cmsg_level, cmsg_type), d)
3023 d[(cmsg_level, cmsg_type)] = cmsg_data
3024 return d
3025
3026 def checkHopLimit(self, ancbufsize, maxhop=255, ignoreflags=0):
3027 # Receive hop limit into ancbufsize bytes of ancillary data
3028 # space. Check that data is MSG, ancillary data is not
3029 # truncated (but ignore any flags in ignoreflags), and hop
3030 # limit is between 0 and maxhop inclusive.
3031 self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
3032 socket.IPV6_RECVHOPLIMIT, 1)
3033 self.misc_event.set()
3034 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
3035 len(MSG), ancbufsize)
3036
3037 self.assertEqual(msg, MSG)
3038 self.checkRecvmsgAddress(addr, self.cli_addr)
3039 self.checkFlags(flags, eor=True, checkunset=socket.MSG_CTRUNC,
3040 ignore=ignoreflags)
3041
3042 self.assertEqual(len(ancdata), 1)
3043 self.assertIsInstance(ancdata[0], tuple)
3044 cmsg_level, cmsg_type, cmsg_data = ancdata[0]
3045 self.assertEqual(cmsg_level, socket.IPPROTO_IPV6)
3046 self.assertEqual(cmsg_type, socket.IPV6_HOPLIMIT)
3047 self.assertIsInstance(cmsg_data, bytes)
3048 self.assertEqual(len(cmsg_data), SIZEOF_INT)
3049 a = array.array("i")
Nadeem Vawda3d1706f2011-08-22 09:46:56 +02003050 a.frombytes(cmsg_data)
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003051 self.assertGreaterEqual(a[0], 0)
3052 self.assertLessEqual(a[0], maxhop)
3053
3054 @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
3055 def testRecvHopLimit(self):
3056 # Test receiving the packet hop limit as ancillary data.
3057 self.checkHopLimit(ancbufsize=10240)
3058
3059 @testRecvHopLimit.client_skip
3060 def _testRecvHopLimit(self):
3061 # Need to wait until server has asked to receive ancillary
3062 # data, as implementations are not required to buffer it
3063 # otherwise.
3064 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3065 self.sendToServer(MSG)
3066
3067 @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
3068 def testRecvHopLimitCMSG_SPACE(self):
3069 # Test receiving hop limit, using CMSG_SPACE to calculate buffer size.
3070 self.checkHopLimit(ancbufsize=socket.CMSG_SPACE(SIZEOF_INT))
3071
3072 @testRecvHopLimitCMSG_SPACE.client_skip
3073 def _testRecvHopLimitCMSG_SPACE(self):
3074 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3075 self.sendToServer(MSG)
3076
3077 # Could test receiving into buffer sized using CMSG_LEN, but RFC
3078 # 3542 says portable applications must provide space for trailing
3079 # padding. Implementations may set MSG_CTRUNC if there isn't
3080 # enough space for the padding.
3081
3082 @requireAttrs(socket.socket, "sendmsg")
3083 @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
3084 def testSetHopLimit(self):
3085 # Test setting hop limit on outgoing packet and receiving it
3086 # at the other end.
3087 self.checkHopLimit(ancbufsize=10240, maxhop=self.hop_limit)
3088
3089 @testSetHopLimit.client_skip
3090 def _testSetHopLimit(self):
3091 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3092 self.assertEqual(
3093 self.sendmsgToServer([MSG],
3094 [(socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT,
3095 array.array("i", [self.hop_limit]))]),
3096 len(MSG))
3097
3098 def checkTrafficClassAndHopLimit(self, ancbufsize, maxhop=255,
3099 ignoreflags=0):
3100 # Receive traffic class and hop limit into ancbufsize bytes of
3101 # ancillary data space. Check that data is MSG, ancillary
3102 # data is not truncated (but ignore any flags in ignoreflags),
3103 # and traffic class and hop limit are in range (hop limit no
3104 # more than maxhop).
3105 self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
3106 socket.IPV6_RECVHOPLIMIT, 1)
3107 self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
3108 socket.IPV6_RECVTCLASS, 1)
3109 self.misc_event.set()
3110 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
3111 len(MSG), ancbufsize)
3112
3113 self.assertEqual(msg, MSG)
3114 self.checkRecvmsgAddress(addr, self.cli_addr)
3115 self.checkFlags(flags, eor=True, checkunset=socket.MSG_CTRUNC,
3116 ignore=ignoreflags)
3117 self.assertEqual(len(ancdata), 2)
3118 ancmap = self.ancillaryMapping(ancdata)
3119
3120 tcdata = ancmap[(socket.IPPROTO_IPV6, socket.IPV6_TCLASS)]
3121 self.assertEqual(len(tcdata), SIZEOF_INT)
3122 a = array.array("i")
Nadeem Vawda3d1706f2011-08-22 09:46:56 +02003123 a.frombytes(tcdata)
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003124 self.assertGreaterEqual(a[0], 0)
3125 self.assertLessEqual(a[0], 255)
3126
3127 hldata = ancmap[(socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT)]
3128 self.assertEqual(len(hldata), SIZEOF_INT)
3129 a = array.array("i")
Nadeem Vawda3d1706f2011-08-22 09:46:56 +02003130 a.frombytes(hldata)
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003131 self.assertGreaterEqual(a[0], 0)
3132 self.assertLessEqual(a[0], maxhop)
3133
3134 @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
3135 "IPV6_RECVTCLASS", "IPV6_TCLASS")
3136 def testRecvTrafficClassAndHopLimit(self):
3137 # Test receiving traffic class and hop limit as ancillary data.
3138 self.checkTrafficClassAndHopLimit(ancbufsize=10240)
3139
3140 @testRecvTrafficClassAndHopLimit.client_skip
3141 def _testRecvTrafficClassAndHopLimit(self):
3142 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3143 self.sendToServer(MSG)
3144
3145 @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
3146 "IPV6_RECVTCLASS", "IPV6_TCLASS")
3147 def testRecvTrafficClassAndHopLimitCMSG_SPACE(self):
3148 # Test receiving traffic class and hop limit, using
3149 # CMSG_SPACE() to calculate buffer size.
3150 self.checkTrafficClassAndHopLimit(
3151 ancbufsize=socket.CMSG_SPACE(SIZEOF_INT) * 2)
3152
3153 @testRecvTrafficClassAndHopLimitCMSG_SPACE.client_skip
3154 def _testRecvTrafficClassAndHopLimitCMSG_SPACE(self):
3155 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3156 self.sendToServer(MSG)
3157
3158 @requireAttrs(socket.socket, "sendmsg")
3159 @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
3160 "IPV6_RECVTCLASS", "IPV6_TCLASS")
3161 def testSetTrafficClassAndHopLimit(self):
3162 # Test setting traffic class and hop limit on outgoing packet,
3163 # and receiving them at the other end.
3164 self.checkTrafficClassAndHopLimit(ancbufsize=10240,
3165 maxhop=self.hop_limit)
3166
3167 @testSetTrafficClassAndHopLimit.client_skip
3168 def _testSetTrafficClassAndHopLimit(self):
3169 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3170 self.assertEqual(
3171 self.sendmsgToServer([MSG],
3172 [(socket.IPPROTO_IPV6, socket.IPV6_TCLASS,
3173 array.array("i", [self.traffic_class])),
3174 (socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT,
3175 array.array("i", [self.hop_limit]))]),
3176 len(MSG))
3177
3178 @requireAttrs(socket.socket, "sendmsg")
3179 @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
3180 "IPV6_RECVTCLASS", "IPV6_TCLASS")
3181 def testOddCmsgSize(self):
3182 # Try to send ancillary data with first item one byte too
3183 # long. Fall back to sending with correct size if this fails,
3184 # and check that second item was handled correctly.
3185 self.checkTrafficClassAndHopLimit(ancbufsize=10240,
3186 maxhop=self.hop_limit)
3187
3188 @testOddCmsgSize.client_skip
3189 def _testOddCmsgSize(self):
3190 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3191 try:
3192 nbytes = self.sendmsgToServer(
3193 [MSG],
3194 [(socket.IPPROTO_IPV6, socket.IPV6_TCLASS,
Nadeem Vawda3d1706f2011-08-22 09:46:56 +02003195 array.array("i", [self.traffic_class]).tobytes() + b"\x00"),
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003196 (socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT,
3197 array.array("i", [self.hop_limit]))])
Andrew Svetlov0832af62012-12-18 23:10:48 +02003198 except OSError as e:
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003199 self.assertIsInstance(e.errno, int)
3200 nbytes = self.sendmsgToServer(
3201 [MSG],
3202 [(socket.IPPROTO_IPV6, socket.IPV6_TCLASS,
3203 array.array("i", [self.traffic_class])),
3204 (socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT,
3205 array.array("i", [self.hop_limit]))])
3206 self.assertEqual(nbytes, len(MSG))
3207
3208 # Tests for proper handling of truncated ancillary data
3209
3210 def checkHopLimitTruncatedHeader(self, ancbufsize, ignoreflags=0):
3211 # Receive hop limit into ancbufsize bytes of ancillary data
3212 # space, which should be too small to contain the ancillary
3213 # data header (if ancbufsize is None, pass no second argument
3214 # to recvmsg()). Check that data is MSG, MSG_CTRUNC is set
3215 # (unless included in ignoreflags), and no ancillary data is
3216 # returned.
3217 self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
3218 socket.IPV6_RECVHOPLIMIT, 1)
3219 self.misc_event.set()
3220 args = () if ancbufsize is None else (ancbufsize,)
3221 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
3222 len(MSG), *args)
3223
3224 self.assertEqual(msg, MSG)
3225 self.checkRecvmsgAddress(addr, self.cli_addr)
3226 self.assertEqual(ancdata, [])
3227 self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC,
3228 ignore=ignoreflags)
3229
3230 @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
3231 def testCmsgTruncNoBufSize(self):
3232 # Check that no ancillary data is received when no ancillary
3233 # buffer size is provided.
3234 self.checkHopLimitTruncatedHeader(ancbufsize=None,
3235 # BSD seems to set
3236 # MSG_CTRUNC only if an item
3237 # has been partially
3238 # received.
3239 ignoreflags=socket.MSG_CTRUNC)
3240
3241 @testCmsgTruncNoBufSize.client_skip
3242 def _testCmsgTruncNoBufSize(self):
3243 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3244 self.sendToServer(MSG)
3245
3246 @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
3247 def testSingleCmsgTrunc0(self):
3248 # Check that no ancillary data is received when ancillary
3249 # buffer size is zero.
3250 self.checkHopLimitTruncatedHeader(ancbufsize=0,
3251 ignoreflags=socket.MSG_CTRUNC)
3252
3253 @testSingleCmsgTrunc0.client_skip
3254 def _testSingleCmsgTrunc0(self):
3255 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3256 self.sendToServer(MSG)
3257
3258 # Check that no ancillary data is returned for various non-zero
3259 # (but still too small) buffer sizes.
3260
3261 @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
3262 def testSingleCmsgTrunc1(self):
3263 self.checkHopLimitTruncatedHeader(ancbufsize=1)
3264
3265 @testSingleCmsgTrunc1.client_skip
3266 def _testSingleCmsgTrunc1(self):
3267 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3268 self.sendToServer(MSG)
3269
3270 @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
3271 def testSingleCmsgTrunc2Int(self):
3272 self.checkHopLimitTruncatedHeader(ancbufsize=2 * SIZEOF_INT)
3273
3274 @testSingleCmsgTrunc2Int.client_skip
3275 def _testSingleCmsgTrunc2Int(self):
3276 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3277 self.sendToServer(MSG)
3278
3279 @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
3280 def testSingleCmsgTruncLen0Minus1(self):
3281 self.checkHopLimitTruncatedHeader(ancbufsize=socket.CMSG_LEN(0) - 1)
3282
3283 @testSingleCmsgTruncLen0Minus1.client_skip
3284 def _testSingleCmsgTruncLen0Minus1(self):
3285 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3286 self.sendToServer(MSG)
3287
3288 @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT")
3289 def testSingleCmsgTruncInData(self):
3290 # Test truncation of a control message inside its associated
3291 # data. The message may be returned with its data truncated,
3292 # or not returned at all.
3293 self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
3294 socket.IPV6_RECVHOPLIMIT, 1)
3295 self.misc_event.set()
3296 msg, ancdata, flags, addr = self.doRecvmsg(
3297 self.serv_sock, len(MSG), socket.CMSG_LEN(SIZEOF_INT) - 1)
3298
3299 self.assertEqual(msg, MSG)
3300 self.checkRecvmsgAddress(addr, self.cli_addr)
3301 self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC)
3302
3303 self.assertLessEqual(len(ancdata), 1)
3304 if ancdata:
3305 cmsg_level, cmsg_type, cmsg_data = ancdata[0]
3306 self.assertEqual(cmsg_level, socket.IPPROTO_IPV6)
3307 self.assertEqual(cmsg_type, socket.IPV6_HOPLIMIT)
3308 self.assertLess(len(cmsg_data), SIZEOF_INT)
3309
3310 @testSingleCmsgTruncInData.client_skip
3311 def _testSingleCmsgTruncInData(self):
3312 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3313 self.sendToServer(MSG)
3314
3315 def checkTruncatedSecondHeader(self, ancbufsize, ignoreflags=0):
3316 # Receive traffic class and hop limit into ancbufsize bytes of
3317 # ancillary data space, which should be large enough to
3318 # contain the first item, but too small to contain the header
3319 # of the second. Check that data is MSG, MSG_CTRUNC is set
3320 # (unless included in ignoreflags), and only one ancillary
3321 # data item is returned.
3322 self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
3323 socket.IPV6_RECVHOPLIMIT, 1)
3324 self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
3325 socket.IPV6_RECVTCLASS, 1)
3326 self.misc_event.set()
3327 msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock,
3328 len(MSG), ancbufsize)
3329
3330 self.assertEqual(msg, MSG)
3331 self.checkRecvmsgAddress(addr, self.cli_addr)
3332 self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC,
3333 ignore=ignoreflags)
3334
3335 self.assertEqual(len(ancdata), 1)
3336 cmsg_level, cmsg_type, cmsg_data = ancdata[0]
3337 self.assertEqual(cmsg_level, socket.IPPROTO_IPV6)
3338 self.assertIn(cmsg_type, {socket.IPV6_TCLASS, socket.IPV6_HOPLIMIT})
3339 self.assertEqual(len(cmsg_data), SIZEOF_INT)
3340 a = array.array("i")
Nadeem Vawda3d1706f2011-08-22 09:46:56 +02003341 a.frombytes(cmsg_data)
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003342 self.assertGreaterEqual(a[0], 0)
3343 self.assertLessEqual(a[0], 255)
3344
3345 # Try the above test with various buffer sizes.
3346
3347 @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
3348 "IPV6_RECVTCLASS", "IPV6_TCLASS")
3349 def testSecondCmsgTrunc0(self):
3350 self.checkTruncatedSecondHeader(socket.CMSG_SPACE(SIZEOF_INT),
3351 ignoreflags=socket.MSG_CTRUNC)
3352
3353 @testSecondCmsgTrunc0.client_skip
3354 def _testSecondCmsgTrunc0(self):
3355 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3356 self.sendToServer(MSG)
3357
3358 @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
3359 "IPV6_RECVTCLASS", "IPV6_TCLASS")
3360 def testSecondCmsgTrunc1(self):
3361 self.checkTruncatedSecondHeader(socket.CMSG_SPACE(SIZEOF_INT) + 1)
3362
3363 @testSecondCmsgTrunc1.client_skip
3364 def _testSecondCmsgTrunc1(self):
3365 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3366 self.sendToServer(MSG)
3367
3368 @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
3369 "IPV6_RECVTCLASS", "IPV6_TCLASS")
3370 def testSecondCmsgTrunc2Int(self):
3371 self.checkTruncatedSecondHeader(socket.CMSG_SPACE(SIZEOF_INT) +
3372 2 * SIZEOF_INT)
3373
3374 @testSecondCmsgTrunc2Int.client_skip
3375 def _testSecondCmsgTrunc2Int(self):
3376 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3377 self.sendToServer(MSG)
3378
3379 @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
3380 "IPV6_RECVTCLASS", "IPV6_TCLASS")
3381 def testSecondCmsgTruncLen0Minus1(self):
3382 self.checkTruncatedSecondHeader(socket.CMSG_SPACE(SIZEOF_INT) +
3383 socket.CMSG_LEN(0) - 1)
3384
3385 @testSecondCmsgTruncLen0Minus1.client_skip
3386 def _testSecondCmsgTruncLen0Minus1(self):
3387 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3388 self.sendToServer(MSG)
3389
3390 @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT",
3391 "IPV6_RECVTCLASS", "IPV6_TCLASS")
3392 def testSecomdCmsgTruncInData(self):
3393 # Test truncation of the second of two control messages inside
3394 # its associated data.
3395 self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
3396 socket.IPV6_RECVHOPLIMIT, 1)
3397 self.serv_sock.setsockopt(socket.IPPROTO_IPV6,
3398 socket.IPV6_RECVTCLASS, 1)
3399 self.misc_event.set()
3400 msg, ancdata, flags, addr = self.doRecvmsg(
3401 self.serv_sock, len(MSG),
3402 socket.CMSG_SPACE(SIZEOF_INT) + socket.CMSG_LEN(SIZEOF_INT) - 1)
3403
3404 self.assertEqual(msg, MSG)
3405 self.checkRecvmsgAddress(addr, self.cli_addr)
3406 self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC)
3407
3408 cmsg_types = {socket.IPV6_TCLASS, socket.IPV6_HOPLIMIT}
3409
3410 cmsg_level, cmsg_type, cmsg_data = ancdata.pop(0)
3411 self.assertEqual(cmsg_level, socket.IPPROTO_IPV6)
3412 cmsg_types.remove(cmsg_type)
3413 self.assertEqual(len(cmsg_data), SIZEOF_INT)
3414 a = array.array("i")
Nadeem Vawda3d1706f2011-08-22 09:46:56 +02003415 a.frombytes(cmsg_data)
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003416 self.assertGreaterEqual(a[0], 0)
3417 self.assertLessEqual(a[0], 255)
3418
3419 if ancdata:
3420 cmsg_level, cmsg_type, cmsg_data = ancdata.pop(0)
3421 self.assertEqual(cmsg_level, socket.IPPROTO_IPV6)
3422 cmsg_types.remove(cmsg_type)
3423 self.assertLess(len(cmsg_data), SIZEOF_INT)
3424
3425 self.assertEqual(ancdata, [])
3426
3427 @testSecomdCmsgTruncInData.client_skip
3428 def _testSecomdCmsgTruncInData(self):
3429 self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout))
3430 self.sendToServer(MSG)
3431
3432
3433# Derive concrete test classes for different socket types.
3434
3435class SendrecvmsgUDPTestBase(SendrecvmsgDgramFlagsBase,
3436 SendrecvmsgConnectionlessBase,
3437 ThreadedSocketTestMixin, UDPTestBase):
3438 pass
3439
3440@requireAttrs(socket.socket, "sendmsg")
3441@unittest.skipUnless(thread, 'Threading required for this test.')
3442class SendmsgUDPTest(SendmsgConnectionlessTests, SendrecvmsgUDPTestBase):
3443 pass
3444
3445@requireAttrs(socket.socket, "recvmsg")
3446@unittest.skipUnless(thread, 'Threading required for this test.')
3447class RecvmsgUDPTest(RecvmsgTests, SendrecvmsgUDPTestBase):
3448 pass
3449
3450@requireAttrs(socket.socket, "recvmsg_into")
3451@unittest.skipUnless(thread, 'Threading required for this test.')
3452class RecvmsgIntoUDPTest(RecvmsgIntoTests, SendrecvmsgUDPTestBase):
3453 pass
3454
3455
3456class SendrecvmsgUDP6TestBase(SendrecvmsgDgramFlagsBase,
3457 SendrecvmsgConnectionlessBase,
3458 ThreadedSocketTestMixin, UDP6TestBase):
Charles-François Natali37114bb2013-07-09 19:15:43 +02003459
3460 def checkRecvmsgAddress(self, addr1, addr2):
3461 # Called to compare the received address with the address of
3462 # the peer, ignoring scope ID
3463 self.assertEqual(addr1[:-1], addr2[:-1])
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003464
3465@requireAttrs(socket.socket, "sendmsg")
Ross Lagerwall8d459f02012-07-08 09:53:57 +02003466@unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.')
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003467@requireSocket("AF_INET6", "SOCK_DGRAM")
3468@unittest.skipUnless(thread, 'Threading required for this test.')
3469class SendmsgUDP6Test(SendmsgConnectionlessTests, SendrecvmsgUDP6TestBase):
3470 pass
3471
3472@requireAttrs(socket.socket, "recvmsg")
Ross Lagerwall8d459f02012-07-08 09:53:57 +02003473@unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.')
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003474@requireSocket("AF_INET6", "SOCK_DGRAM")
3475@unittest.skipUnless(thread, 'Threading required for this test.')
3476class RecvmsgUDP6Test(RecvmsgTests, SendrecvmsgUDP6TestBase):
3477 pass
3478
3479@requireAttrs(socket.socket, "recvmsg_into")
Ross Lagerwall8d459f02012-07-08 09:53:57 +02003480@unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.')
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003481@requireSocket("AF_INET6", "SOCK_DGRAM")
3482@unittest.skipUnless(thread, 'Threading required for this test.')
3483class RecvmsgIntoUDP6Test(RecvmsgIntoTests, SendrecvmsgUDP6TestBase):
3484 pass
3485
3486@requireAttrs(socket.socket, "recvmsg")
Ross Lagerwall8d459f02012-07-08 09:53:57 +02003487@unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.')
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003488@requireAttrs(socket, "IPPROTO_IPV6")
3489@requireSocket("AF_INET6", "SOCK_DGRAM")
3490@unittest.skipUnless(thread, 'Threading required for this test.')
3491class RecvmsgRFC3542AncillaryUDP6Test(RFC3542AncillaryTest,
3492 SendrecvmsgUDP6TestBase):
3493 pass
3494
3495@requireAttrs(socket.socket, "recvmsg_into")
Ross Lagerwall8d459f02012-07-08 09:53:57 +02003496@unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.')
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003497@requireAttrs(socket, "IPPROTO_IPV6")
3498@requireSocket("AF_INET6", "SOCK_DGRAM")
3499@unittest.skipUnless(thread, 'Threading required for this test.')
3500class RecvmsgIntoRFC3542AncillaryUDP6Test(RecvmsgIntoMixin,
3501 RFC3542AncillaryTest,
3502 SendrecvmsgUDP6TestBase):
3503 pass
3504
3505
3506class SendrecvmsgTCPTestBase(SendrecvmsgConnectedBase,
3507 ConnectedStreamTestMixin, TCPTestBase):
3508 pass
3509
3510@requireAttrs(socket.socket, "sendmsg")
3511@unittest.skipUnless(thread, 'Threading required for this test.')
3512class SendmsgTCPTest(SendmsgStreamTests, SendrecvmsgTCPTestBase):
3513 pass
3514
3515@requireAttrs(socket.socket, "recvmsg")
3516@unittest.skipUnless(thread, 'Threading required for this test.')
3517class RecvmsgTCPTest(RecvmsgTests, RecvmsgGenericStreamTests,
3518 SendrecvmsgTCPTestBase):
3519 pass
3520
3521@requireAttrs(socket.socket, "recvmsg_into")
3522@unittest.skipUnless(thread, 'Threading required for this test.')
3523class RecvmsgIntoTCPTest(RecvmsgIntoTests, RecvmsgGenericStreamTests,
3524 SendrecvmsgTCPTestBase):
3525 pass
3526
3527
3528class SendrecvmsgSCTPStreamTestBase(SendrecvmsgSCTPFlagsBase,
3529 SendrecvmsgConnectedBase,
3530 ConnectedStreamTestMixin, SCTPStreamBase):
3531 pass
3532
3533@requireAttrs(socket.socket, "sendmsg")
3534@requireSocket("AF_INET", "SOCK_STREAM", "IPPROTO_SCTP")
3535@unittest.skipUnless(thread, 'Threading required for this test.')
3536class SendmsgSCTPStreamTest(SendmsgStreamTests, SendrecvmsgSCTPStreamTestBase):
3537 pass
3538
3539@requireAttrs(socket.socket, "recvmsg")
3540@requireSocket("AF_INET", "SOCK_STREAM", "IPPROTO_SCTP")
3541@unittest.skipUnless(thread, 'Threading required for this test.')
3542class RecvmsgSCTPStreamTest(RecvmsgTests, RecvmsgGenericStreamTests,
3543 SendrecvmsgSCTPStreamTestBase):
Antoine Pitrou92f8b002012-12-16 16:40:04 +01003544
3545 def testRecvmsgEOF(self):
3546 try:
3547 super(RecvmsgSCTPStreamTest, self).testRecvmsgEOF()
3548 except OSError as e:
3549 if e.errno != errno.ENOTCONN:
3550 raise
3551 self.skipTest("sporadic ENOTCONN (kernel issue?) - see issue #13876")
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003552
3553@requireAttrs(socket.socket, "recvmsg_into")
3554@requireSocket("AF_INET", "SOCK_STREAM", "IPPROTO_SCTP")
3555@unittest.skipUnless(thread, 'Threading required for this test.')
3556class RecvmsgIntoSCTPStreamTest(RecvmsgIntoTests, RecvmsgGenericStreamTests,
3557 SendrecvmsgSCTPStreamTestBase):
Antoine Pitroud5a070f2012-12-18 23:44:36 +01003558
3559 def testRecvmsgEOF(self):
3560 try:
3561 super(RecvmsgIntoSCTPStreamTest, self).testRecvmsgEOF()
3562 except OSError as e:
3563 if e.errno != errno.ENOTCONN:
3564 raise
3565 self.skipTest("sporadic ENOTCONN (kernel issue?) - see issue #13876")
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003566
3567
3568class SendrecvmsgUnixStreamTestBase(SendrecvmsgConnectedBase,
3569 ConnectedStreamTestMixin, UnixStreamBase):
3570 pass
3571
3572@requireAttrs(socket.socket, "sendmsg")
3573@requireAttrs(socket, "AF_UNIX")
3574@unittest.skipUnless(thread, 'Threading required for this test.')
3575class SendmsgUnixStreamTest(SendmsgStreamTests, SendrecvmsgUnixStreamTestBase):
3576 pass
3577
3578@requireAttrs(socket.socket, "recvmsg")
3579@requireAttrs(socket, "AF_UNIX")
3580@unittest.skipUnless(thread, 'Threading required for this test.')
3581class RecvmsgUnixStreamTest(RecvmsgTests, RecvmsgGenericStreamTests,
3582 SendrecvmsgUnixStreamTestBase):
3583 pass
3584
3585@requireAttrs(socket.socket, "recvmsg_into")
3586@requireAttrs(socket, "AF_UNIX")
3587@unittest.skipUnless(thread, 'Threading required for this test.')
3588class RecvmsgIntoUnixStreamTest(RecvmsgIntoTests, RecvmsgGenericStreamTests,
3589 SendrecvmsgUnixStreamTestBase):
3590 pass
3591
3592@requireAttrs(socket.socket, "sendmsg", "recvmsg")
3593@requireAttrs(socket, "AF_UNIX", "SOL_SOCKET", "SCM_RIGHTS")
3594@unittest.skipUnless(thread, 'Threading required for this test.')
3595class RecvmsgSCMRightsStreamTest(SCMRightsTest, SendrecvmsgUnixStreamTestBase):
3596 pass
3597
3598@requireAttrs(socket.socket, "sendmsg", "recvmsg_into")
3599@requireAttrs(socket, "AF_UNIX", "SOL_SOCKET", "SCM_RIGHTS")
3600@unittest.skipUnless(thread, 'Threading required for this test.')
3601class RecvmsgIntoSCMRightsStreamTest(RecvmsgIntoMixin, SCMRightsTest,
3602 SendrecvmsgUnixStreamTestBase):
3603 pass
3604
3605
3606# Test interrupting the interruptible send/receive methods with a
3607# signal when a timeout is set. These tests avoid having multiple
3608# threads alive during the test so that the OS cannot deliver the
3609# signal to the wrong one.
3610
3611class InterruptedTimeoutBase(unittest.TestCase):
3612 # Base class for interrupted send/receive tests. Installs an
3613 # empty handler for SIGALRM and removes it on teardown, along with
3614 # any scheduled alarms.
3615
3616 def setUp(self):
3617 super().setUp()
3618 orig_alrm_handler = signal.signal(signal.SIGALRM,
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003619 lambda signum, frame: 1 / 0)
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003620 self.addCleanup(signal.signal, signal.SIGALRM, orig_alrm_handler)
3621 self.addCleanup(self.setAlarm, 0)
3622
3623 # Timeout for socket operations
3624 timeout = 4.0
3625
3626 # Provide setAlarm() method to schedule delivery of SIGALRM after
3627 # given number of seconds, or cancel it if zero, and an
3628 # appropriate time value to use. Use setitimer() if available.
3629 if hasattr(signal, "setitimer"):
3630 alarm_time = 0.05
3631
3632 def setAlarm(self, seconds):
3633 signal.setitimer(signal.ITIMER_REAL, seconds)
3634 else:
3635 # Old systems may deliver the alarm up to one second early
3636 alarm_time = 2
3637
3638 def setAlarm(self, seconds):
3639 signal.alarm(seconds)
3640
3641
3642# Require siginterrupt() in order to ensure that system calls are
3643# interrupted by default.
3644@requireAttrs(signal, "siginterrupt")
3645@unittest.skipUnless(hasattr(signal, "alarm") or hasattr(signal, "setitimer"),
3646 "Don't have signal.alarm or signal.setitimer")
3647class InterruptedRecvTimeoutTest(InterruptedTimeoutBase, UDPTestBase):
3648 # Test interrupting the recv*() methods with signals when a
3649 # timeout is set.
3650
3651 def setUp(self):
3652 super().setUp()
3653 self.serv.settimeout(self.timeout)
3654
3655 def checkInterruptedRecv(self, func, *args, **kwargs):
Charles-François Natali26dd5ed2015-02-07 13:29:15 +00003656 # Check that func(*args, **kwargs) raises
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003657 # errno of EINTR when interrupted by a signal.
3658 self.setAlarm(self.alarm_time)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003659 with self.assertRaises(ZeroDivisionError) as cm:
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003660 func(*args, **kwargs)
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003661
3662 def testInterruptedRecvTimeout(self):
3663 self.checkInterruptedRecv(self.serv.recv, 1024)
3664
3665 def testInterruptedRecvIntoTimeout(self):
3666 self.checkInterruptedRecv(self.serv.recv_into, bytearray(1024))
3667
3668 def testInterruptedRecvfromTimeout(self):
3669 self.checkInterruptedRecv(self.serv.recvfrom, 1024)
3670
3671 def testInterruptedRecvfromIntoTimeout(self):
3672 self.checkInterruptedRecv(self.serv.recvfrom_into, bytearray(1024))
3673
3674 @requireAttrs(socket.socket, "recvmsg")
3675 def testInterruptedRecvmsgTimeout(self):
3676 self.checkInterruptedRecv(self.serv.recvmsg, 1024)
3677
3678 @requireAttrs(socket.socket, "recvmsg_into")
3679 def testInterruptedRecvmsgIntoTimeout(self):
3680 self.checkInterruptedRecv(self.serv.recvmsg_into, [bytearray(1024)])
3681
3682
3683# Require siginterrupt() in order to ensure that system calls are
3684# interrupted by default.
3685@requireAttrs(signal, "siginterrupt")
3686@unittest.skipUnless(hasattr(signal, "alarm") or hasattr(signal, "setitimer"),
3687 "Don't have signal.alarm or signal.setitimer")
3688@unittest.skipUnless(thread, 'Threading required for this test.')
3689class InterruptedSendTimeoutTest(InterruptedTimeoutBase,
3690 ThreadSafeCleanupTestCase,
3691 SocketListeningTestMixin, TCPTestBase):
3692 # Test interrupting the interruptible send*() methods with signals
3693 # when a timeout is set.
3694
3695 def setUp(self):
3696 super().setUp()
3697 self.serv_conn = self.newSocket()
3698 self.addCleanup(self.serv_conn.close)
3699 # Use a thread to complete the connection, but wait for it to
3700 # terminate before running the test, so that there is only one
3701 # thread to accept the signal.
3702 cli_thread = threading.Thread(target=self.doConnect)
3703 cli_thread.start()
3704 self.cli_conn, addr = self.serv.accept()
3705 self.addCleanup(self.cli_conn.close)
3706 cli_thread.join()
3707 self.serv_conn.settimeout(self.timeout)
3708
3709 def doConnect(self):
3710 self.serv_conn.connect(self.serv_addr)
3711
3712 def checkInterruptedSend(self, func, *args, **kwargs):
3713 # Check that func(*args, **kwargs), run in a loop, raises
Andrew Svetlov0832af62012-12-18 23:10:48 +02003714 # OSError with an errno of EINTR when interrupted by a
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003715 # signal.
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003716 with self.assertRaises(ZeroDivisionError) as cm:
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003717 while True:
3718 self.setAlarm(self.alarm_time)
3719 func(*args, **kwargs)
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003720
Ned Deilyc5640382014-02-03 13:58:31 -08003721 # Issue #12958: The following tests have problems on OS X prior to 10.7
3722 @support.requires_mac_ver(10, 7)
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003723 def testInterruptedSendTimeout(self):
3724 self.checkInterruptedSend(self.serv_conn.send, b"a"*512)
3725
Ned Deilyc5640382014-02-03 13:58:31 -08003726 @support.requires_mac_ver(10, 7)
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003727 def testInterruptedSendtoTimeout(self):
3728 # Passing an actual address here as Python's wrapper for
3729 # sendto() doesn't allow passing a zero-length one; POSIX
3730 # requires that the address is ignored since the socket is
3731 # connection-mode, however.
3732 self.checkInterruptedSend(self.serv_conn.sendto, b"a"*512,
3733 self.serv_addr)
3734
Ned Deilyc5640382014-02-03 13:58:31 -08003735 @support.requires_mac_ver(10, 7)
Nick Coghlan96fe56a2011-08-22 11:55:57 +10003736 @requireAttrs(socket.socket, "sendmsg")
3737 def testInterruptedSendmsgTimeout(self):
3738 self.checkInterruptedSend(self.serv_conn.sendmsg, [b"a"*512])
3739
3740
Victor Stinner45df8202010-04-28 22:31:17 +00003741@unittest.skipUnless(thread, 'Threading required for this test.')
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003742class TCPCloserTest(ThreadedTCPSocketTest):
3743
3744 def testClose(self):
3745 conn, addr = self.serv.accept()
3746 conn.close()
3747
3748 sd = self.cli
3749 read, write, err = select.select([sd], [], [], 1.0)
3750 self.assertEqual(read, [sd])
Guido van Rossum7d0a8262007-05-21 23:13:11 +00003751 self.assertEqual(sd.recv(1), b'')
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003752
Jeremy Hylton5accbdb2007-08-03 20:40:09 +00003753 # Calling close() many times should be safe.
3754 conn.close()
3755 conn.close()
3756
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003757 def _testClose(self):
Christian Heimes5e696852008-04-09 08:37:03 +00003758 self.cli.connect((HOST, self.port))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003759 time.sleep(1.0)
3760
Victor Stinner45df8202010-04-28 22:31:17 +00003761@unittest.skipUnless(thread, 'Threading required for this test.')
Dave Cole331708b2004-08-09 04:51:41 +00003762class BasicSocketPairTest(SocketPairTest):
3763
3764 def __init__(self, methodName='runTest'):
3765 SocketPairTest.__init__(self, methodName=methodName)
3766
Antoine Pitrou2e55fec2010-09-14 21:24:25 +00003767 def _check_defaults(self, sock):
3768 self.assertIsInstance(sock, socket.socket)
3769 if hasattr(socket, 'AF_UNIX'):
3770 self.assertEqual(sock.family, socket.AF_UNIX)
3771 else:
3772 self.assertEqual(sock.family, socket.AF_INET)
3773 self.assertEqual(sock.type, socket.SOCK_STREAM)
3774 self.assertEqual(sock.proto, 0)
3775
Antoine Pitrou9e0b8642010-09-14 18:00:02 +00003776 def _testDefaults(self):
Antoine Pitrou2e55fec2010-09-14 21:24:25 +00003777 self._check_defaults(self.cli)
Antoine Pitrou9e0b8642010-09-14 18:00:02 +00003778
3779 def testDefaults(self):
Antoine Pitrou2e55fec2010-09-14 21:24:25 +00003780 self._check_defaults(self.serv)
Antoine Pitrou9e0b8642010-09-14 18:00:02 +00003781
Dave Cole331708b2004-08-09 04:51:41 +00003782 def testRecv(self):
3783 msg = self.serv.recv(1024)
3784 self.assertEqual(msg, MSG)
3785
3786 def _testRecv(self):
3787 self.cli.send(MSG)
3788
3789 def testSend(self):
3790 self.serv.send(MSG)
3791
3792 def _testSend(self):
3793 msg = self.cli.recv(1024)
3794 self.assertEqual(msg, MSG)
3795
Victor Stinner45df8202010-04-28 22:31:17 +00003796@unittest.skipUnless(thread, 'Threading required for this test.')
Guido van Rossum24e4af82002-06-12 19:18:08 +00003797class NonBlockingTCPTests(ThreadedTCPSocketTest):
3798
3799 def __init__(self, methodName='runTest'):
3800 ThreadedTCPSocketTest.__init__(self, methodName=methodName)
3801
3802 def testSetBlocking(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00003803 # Testing whether set blocking works
Serhiy Storchaka45cb7f62013-01-15 11:08:30 +02003804 self.serv.setblocking(True)
3805 self.assertIsNone(self.serv.gettimeout())
3806 self.serv.setblocking(False)
3807 self.assertEqual(self.serv.gettimeout(), 0.0)
Guido van Rossum24e4af82002-06-12 19:18:08 +00003808 start = time.time()
3809 try:
3810 self.serv.accept()
Andrew Svetlov0832af62012-12-18 23:10:48 +02003811 except OSError:
Guido van Rossum24e4af82002-06-12 19:18:08 +00003812 pass
3813 end = time.time()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003814 self.assertTrue((end - start) < 1.0, "Error setting non-blocking mode.")
Guido van Rossum24e4af82002-06-12 19:18:08 +00003815
3816 def _testSetBlocking(self):
Barry Warsaw6870bba2001-03-23 17:40:16 +00003817 pass
Barry Warsawcf3d4b51997-01-03 20:03:32 +00003818
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02003819 @support.cpython_only
3820 def testSetBlocking_overflow(self):
3821 # Issue 15989
3822 import _testcapi
3823 if _testcapi.UINT_MAX >= _testcapi.ULONG_MAX:
3824 self.skipTest('needs UINT_MAX < ULONG_MAX')
3825 self.serv.setblocking(False)
3826 self.assertEqual(self.serv.gettimeout(), 0.0)
3827 self.serv.setblocking(_testcapi.UINT_MAX + 1)
3828 self.assertIsNone(self.serv.gettimeout())
3829
3830 _testSetBlocking_overflow = support.cpython_only(_testSetBlocking)
3831
Serhiy Storchaka43767632013-11-03 21:31:38 +02003832 @unittest.skipUnless(hasattr(socket, 'SOCK_NONBLOCK'),
3833 'test needs socket.SOCK_NONBLOCK')
3834 @support.requires_linux_version(2, 6, 28)
3835 def testInitNonBlocking(self):
3836 # reinit server socket
3837 self.serv.close()
3838 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM |
3839 socket.SOCK_NONBLOCK)
3840 self.port = support.bind_port(self.serv)
Charles-François Natali6e204602014-07-23 19:28:13 +01003841 self.serv.listen()
Serhiy Storchaka43767632013-11-03 21:31:38 +02003842 # actual testing
3843 start = time.time()
3844 try:
3845 self.serv.accept()
3846 except OSError:
Antoine Pitroub1c54962010-10-14 15:05:38 +00003847 pass
Serhiy Storchaka43767632013-11-03 21:31:38 +02003848 end = time.time()
3849 self.assertTrue((end - start) < 1.0, "Error creating with non-blocking mode.")
3850
3851 def _testInitNonBlocking(self):
3852 pass
Antoine Pitroub1c54962010-10-14 15:05:38 +00003853
Antoine Pitrou600232b2011-01-05 21:03:42 +00003854 def testInheritFlags(self):
3855 # Issue #7995: when calling accept() on a listening socket with a
3856 # timeout, the resulting socket should not be non-blocking.
3857 self.serv.settimeout(10)
3858 try:
3859 conn, addr = self.serv.accept()
3860 message = conn.recv(len(MSG))
3861 finally:
3862 conn.close()
3863 self.serv.settimeout(None)
3864
3865 def _testInheritFlags(self):
3866 time.sleep(0.1)
3867 self.cli.connect((HOST, self.port))
3868 time.sleep(0.5)
3869 self.cli.send(MSG)
3870
Guido van Rossum24e4af82002-06-12 19:18:08 +00003871 def testAccept(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00003872 # Testing non-blocking accept
Guido van Rossum24e4af82002-06-12 19:18:08 +00003873 self.serv.setblocking(0)
Guido van Rossum41360a41998-03-26 19:42:58 +00003874 try:
Guido van Rossum24e4af82002-06-12 19:18:08 +00003875 conn, addr = self.serv.accept()
Andrew Svetlov0832af62012-12-18 23:10:48 +02003876 except OSError:
Guido van Rossum24e4af82002-06-12 19:18:08 +00003877 pass
3878 else:
3879 self.fail("Error trying to do non-blocking accept.")
3880 read, write, err = select.select([self.serv], [], [])
3881 if self.serv in read:
3882 conn, addr = self.serv.accept()
Benjamin Petersond9dbf492015-10-24 20:06:04 -07003883 self.assertIsNone(conn.gettimeout())
Brian Curtin21ebbb72010-11-02 02:07:09 +00003884 conn.close()
Guido van Rossum24e4af82002-06-12 19:18:08 +00003885 else:
3886 self.fail("Error trying to do accept after select.")
Guido van Rossum67f7a382002-06-06 21:08:16 +00003887
Guido van Rossum24e4af82002-06-12 19:18:08 +00003888 def _testAccept(self):
Guido van Rossumb6cc7d22002-07-19 12:46:46 +00003889 time.sleep(0.1)
Christian Heimes5e696852008-04-09 08:37:03 +00003890 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +00003891
3892 def testConnect(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00003893 # Testing non-blocking connect
Guido van Rossum24e4af82002-06-12 19:18:08 +00003894 conn, addr = self.serv.accept()
Brian Curtin21ebbb72010-11-02 02:07:09 +00003895 conn.close()
Guido van Rossum24e4af82002-06-12 19:18:08 +00003896
3897 def _testConnect(self):
Guido van Rossum7b8bac12002-06-13 16:07:04 +00003898 self.cli.settimeout(10)
Christian Heimes5e696852008-04-09 08:37:03 +00003899 self.cli.connect((HOST, self.port))
Guido van Rossum24e4af82002-06-12 19:18:08 +00003900
3901 def testRecv(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00003902 # Testing non-blocking recv
Guido van Rossum24e4af82002-06-12 19:18:08 +00003903 conn, addr = self.serv.accept()
3904 conn.setblocking(0)
3905 try:
3906 msg = conn.recv(len(MSG))
Andrew Svetlov0832af62012-12-18 23:10:48 +02003907 except OSError:
Guido van Rossum24e4af82002-06-12 19:18:08 +00003908 pass
3909 else:
3910 self.fail("Error trying to do non-blocking recv.")
3911 read, write, err = select.select([conn], [], [])
3912 if conn in read:
3913 msg = conn.recv(len(MSG))
Brian Curtin21ebbb72010-11-02 02:07:09 +00003914 conn.close()
Guido van Rossum76489682002-06-12 20:38:30 +00003915 self.assertEqual(msg, MSG)
Guido van Rossum24e4af82002-06-12 19:18:08 +00003916 else:
3917 self.fail("Error during select call to non-blocking socket.")
3918
3919 def _testRecv(self):
Christian Heimes5e696852008-04-09 08:37:03 +00003920 self.cli.connect((HOST, self.port))
Guido van Rossumb6cc7d22002-07-19 12:46:46 +00003921 time.sleep(0.1)
Guido van Rossum24e4af82002-06-12 19:18:08 +00003922 self.cli.send(MSG)
3923
Victor Stinner45df8202010-04-28 22:31:17 +00003924@unittest.skipUnless(thread, 'Threading required for this test.')
Guido van Rossum24e4af82002-06-12 19:18:08 +00003925class FileObjectClassTestCase(SocketConnectedTest):
Jeremy Hylton5accbdb2007-08-03 20:40:09 +00003926 """Unit tests for the object returned by socket.makefile()
3927
Antoine Pitrou834bd812010-10-13 16:17:14 +00003928 self.read_file is the io object returned by makefile() on
Jeremy Hylton5accbdb2007-08-03 20:40:09 +00003929 the client connection. You can read from this file to
3930 get output from the server.
3931
Antoine Pitrou834bd812010-10-13 16:17:14 +00003932 self.write_file is the io object returned by makefile() on the
Jeremy Hylton5accbdb2007-08-03 20:40:09 +00003933 server connection. You can write to this file to send output
3934 to the client.
3935 """
Guido van Rossum24e4af82002-06-12 19:18:08 +00003936
Guido van Rossume9f66142002-08-07 15:46:19 +00003937 bufsize = -1 # Use default buffer size
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00003938 encoding = 'utf-8'
Antoine Pitrou834bd812010-10-13 16:17:14 +00003939 errors = 'strict'
3940 newline = None
3941
3942 read_mode = 'rb'
3943 read_msg = MSG
3944 write_mode = 'wb'
3945 write_msg = MSG
Guido van Rossume9f66142002-08-07 15:46:19 +00003946
Guido van Rossum24e4af82002-06-12 19:18:08 +00003947 def __init__(self, methodName='runTest'):
3948 SocketConnectedTest.__init__(self, methodName=methodName)
3949
3950 def setUp(self):
Antoine Pitrou98b46702010-09-18 22:59:00 +00003951 self.evt1, self.evt2, self.serv_finished, self.cli_finished = [
3952 threading.Event() for i in range(4)]
Guido van Rossum24e4af82002-06-12 19:18:08 +00003953 SocketConnectedTest.setUp(self)
Antoine Pitrou834bd812010-10-13 16:17:14 +00003954 self.read_file = self.cli_conn.makefile(
3955 self.read_mode, self.bufsize,
3956 encoding = self.encoding,
3957 errors = self.errors,
3958 newline = self.newline)
Guido van Rossum24e4af82002-06-12 19:18:08 +00003959
3960 def tearDown(self):
Antoine Pitrou98b46702010-09-18 22:59:00 +00003961 self.serv_finished.set()
Antoine Pitrou834bd812010-10-13 16:17:14 +00003962 self.read_file.close()
3963 self.assertTrue(self.read_file.closed)
3964 self.read_file = None
Guido van Rossum24e4af82002-06-12 19:18:08 +00003965 SocketConnectedTest.tearDown(self)
3966
3967 def clientSetUp(self):
3968 SocketConnectedTest.clientSetUp(self)
Antoine Pitrou834bd812010-10-13 16:17:14 +00003969 self.write_file = self.serv_conn.makefile(
3970 self.write_mode, self.bufsize,
3971 encoding = self.encoding,
3972 errors = self.errors,
3973 newline = self.newline)
Guido van Rossum24e4af82002-06-12 19:18:08 +00003974
3975 def clientTearDown(self):
Antoine Pitrou98b46702010-09-18 22:59:00 +00003976 self.cli_finished.set()
Antoine Pitrou834bd812010-10-13 16:17:14 +00003977 self.write_file.close()
3978 self.assertTrue(self.write_file.closed)
3979 self.write_file = None
Guido van Rossum24e4af82002-06-12 19:18:08 +00003980 SocketConnectedTest.clientTearDown(self)
3981
Antoine Pitrou68e5c042011-02-25 23:07:44 +00003982 def testReadAfterTimeout(self):
3983 # Issue #7322: A file object must disallow further reads
3984 # after a timeout has occurred.
3985 self.cli_conn.settimeout(1)
3986 self.read_file.read(3)
3987 # First read raises a timeout
3988 self.assertRaises(socket.timeout, self.read_file.read, 1)
3989 # Second read is disallowed
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02003990 with self.assertRaises(OSError) as ctx:
Antoine Pitrou68e5c042011-02-25 23:07:44 +00003991 self.read_file.read(1)
3992 self.assertIn("cannot read from timed out object", str(ctx.exception))
3993
3994 def _testReadAfterTimeout(self):
3995 self.write_file.write(self.write_msg[0:3])
3996 self.write_file.flush()
3997 self.serv_finished.wait()
3998
Guido van Rossum24e4af82002-06-12 19:18:08 +00003999 def testSmallRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00004000 # Performing small file read test
Antoine Pitrou834bd812010-10-13 16:17:14 +00004001 first_seg = self.read_file.read(len(self.read_msg)-3)
4002 second_seg = self.read_file.read(3)
Guido van Rossumab659962002-06-12 21:29:43 +00004003 msg = first_seg + second_seg
Antoine Pitrou834bd812010-10-13 16:17:14 +00004004 self.assertEqual(msg, self.read_msg)
Guido van Rossum24e4af82002-06-12 19:18:08 +00004005
4006 def _testSmallRead(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00004007 self.write_file.write(self.write_msg)
4008 self.write_file.flush()
Guido van Rossum24e4af82002-06-12 19:18:08 +00004009
Guido van Rossum8c943832002-08-08 01:00:28 +00004010 def testFullRead(self):
4011 # read until EOF
Antoine Pitrou834bd812010-10-13 16:17:14 +00004012 msg = self.read_file.read()
4013 self.assertEqual(msg, self.read_msg)
Guido van Rossum8c943832002-08-08 01:00:28 +00004014
4015 def _testFullRead(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00004016 self.write_file.write(self.write_msg)
4017 self.write_file.close()
Guido van Rossum8c943832002-08-08 01:00:28 +00004018
Guido van Rossum24e4af82002-06-12 19:18:08 +00004019 def testUnbufferedRead(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00004020 # Performing unbuffered file read test
Antoine Pitrou834bd812010-10-13 16:17:14 +00004021 buf = type(self.read_msg)()
Guido van Rossum24e4af82002-06-12 19:18:08 +00004022 while 1:
Antoine Pitrou834bd812010-10-13 16:17:14 +00004023 char = self.read_file.read(1)
Guido van Rossum8c943832002-08-08 01:00:28 +00004024 if not char:
Guido van Rossum24e4af82002-06-12 19:18:08 +00004025 break
Guido van Rossum8c943832002-08-08 01:00:28 +00004026 buf += char
Antoine Pitrou834bd812010-10-13 16:17:14 +00004027 self.assertEqual(buf, self.read_msg)
Guido van Rossum24e4af82002-06-12 19:18:08 +00004028
4029 def _testUnbufferedRead(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00004030 self.write_file.write(self.write_msg)
4031 self.write_file.flush()
Guido van Rossum24e4af82002-06-12 19:18:08 +00004032
4033 def testReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00004034 # Performing file readline test
Antoine Pitrou834bd812010-10-13 16:17:14 +00004035 line = self.read_file.readline()
4036 self.assertEqual(line, self.read_msg)
Guido van Rossum24e4af82002-06-12 19:18:08 +00004037
4038 def _testReadline(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00004039 self.write_file.write(self.write_msg)
4040 self.write_file.flush()
Guido van Rossum24e4af82002-06-12 19:18:08 +00004041
Jeremy Hylton5accbdb2007-08-03 20:40:09 +00004042 def testCloseAfterMakefile(self):
4043 # The file returned by makefile should keep the socket open.
4044 self.cli_conn.close()
4045 # read until EOF
Antoine Pitrou834bd812010-10-13 16:17:14 +00004046 msg = self.read_file.read()
4047 self.assertEqual(msg, self.read_msg)
Jeremy Hylton5accbdb2007-08-03 20:40:09 +00004048
4049 def _testCloseAfterMakefile(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00004050 self.write_file.write(self.write_msg)
4051 self.write_file.flush()
Jeremy Hylton5accbdb2007-08-03 20:40:09 +00004052
4053 def testMakefileAfterMakefileClose(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00004054 self.read_file.close()
Jeremy Hylton5accbdb2007-08-03 20:40:09 +00004055 msg = self.cli_conn.recv(len(MSG))
Antoine Pitrou834bd812010-10-13 16:17:14 +00004056 if isinstance(self.read_msg, str):
4057 msg = msg.decode()
4058 self.assertEqual(msg, self.read_msg)
Jeremy Hylton5accbdb2007-08-03 20:40:09 +00004059
4060 def _testMakefileAfterMakefileClose(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00004061 self.write_file.write(self.write_msg)
4062 self.write_file.flush()
Jeremy Hylton5accbdb2007-08-03 20:40:09 +00004063
Tim Peters116d83c2004-03-28 02:20:45 +00004064 def testClosedAttr(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00004065 self.assertTrue(not self.read_file.closed)
Tim Peters116d83c2004-03-28 02:20:45 +00004066
4067 def _testClosedAttr(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00004068 self.assertTrue(not self.write_file.closed)
Tim Peters116d83c2004-03-28 02:20:45 +00004069
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +00004070 def testAttributes(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00004071 self.assertEqual(self.read_file.mode, self.read_mode)
4072 self.assertEqual(self.read_file.name, self.cli_conn.fileno())
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +00004073
4074 def _testAttributes(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00004075 self.assertEqual(self.write_file.mode, self.write_mode)
4076 self.assertEqual(self.write_file.name, self.serv_conn.fileno())
Amaury Forgeot d'Arc9d24ff02008-11-20 23:15:52 +00004077
Gregory P. Smithde3369f2009-01-12 04:50:11 +00004078 def testRealClose(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00004079 self.read_file.close()
4080 self.assertRaises(ValueError, self.read_file.fileno)
Gregory P. Smithde3369f2009-01-12 04:50:11 +00004081 self.cli_conn.close()
Andrew Svetlov0832af62012-12-18 23:10:48 +02004082 self.assertRaises(OSError, self.cli_conn.getsockname)
Gregory P. Smithde3369f2009-01-12 04:50:11 +00004083
4084 def _testRealClose(self):
4085 pass
4086
4087
Guido van Rossume9f66142002-08-07 15:46:19 +00004088class UnbufferedFileObjectClassTestCase(FileObjectClassTestCase):
4089
4090 """Repeat the tests from FileObjectClassTestCase with bufsize==0.
Tim Peters469cdad2002-08-08 20:19:19 +00004091
Guido van Rossume9f66142002-08-07 15:46:19 +00004092 In this case (and in this case only), it should be possible to
4093 create a file object, read a line from it, create another file
4094 object, read another line from it, without loss of data in the
Georg Brandl24420152008-05-26 16:32:26 +00004095 first file object's buffer. Note that http.client relies on this
Guido van Rossume9f66142002-08-07 15:46:19 +00004096 when reading multiple requests from the same socket."""
4097
4098 bufsize = 0 # Use unbuffered mode
4099
4100 def testUnbufferedReadline(self):
Guido van Rossum8c943832002-08-08 01:00:28 +00004101 # Read a line, create a new file object, read another line with it
Antoine Pitrou834bd812010-10-13 16:17:14 +00004102 line = self.read_file.readline() # first line
4103 self.assertEqual(line, b"A. " + self.write_msg) # first line
4104 self.read_file = self.cli_conn.makefile('rb', 0)
4105 line = self.read_file.readline() # second line
4106 self.assertEqual(line, b"B. " + self.write_msg) # second line
Guido van Rossume9f66142002-08-07 15:46:19 +00004107
4108 def _testUnbufferedReadline(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00004109 self.write_file.write(b"A. " + self.write_msg)
4110 self.write_file.write(b"B. " + self.write_msg)
4111 self.write_file.flush()
Guido van Rossume9f66142002-08-07 15:46:19 +00004112
Gregory P. Smithde3369f2009-01-12 04:50:11 +00004113 def testMakefileClose(self):
4114 # The file returned by makefile should keep the socket open...
4115 self.cli_conn.close()
4116 msg = self.cli_conn.recv(1024)
Antoine Pitrou834bd812010-10-13 16:17:14 +00004117 self.assertEqual(msg, self.read_msg)
Gregory P. Smithde3369f2009-01-12 04:50:11 +00004118 # ...until the file is itself closed
Antoine Pitrou834bd812010-10-13 16:17:14 +00004119 self.read_file.close()
Andrew Svetlov0832af62012-12-18 23:10:48 +02004120 self.assertRaises(OSError, self.cli_conn.recv, 1024)
Gregory P. Smithde3369f2009-01-12 04:50:11 +00004121
4122 def _testMakefileClose(self):
Antoine Pitrou834bd812010-10-13 16:17:14 +00004123 self.write_file.write(self.write_msg)
4124 self.write_file.flush()
Gregory P. Smithde3369f2009-01-12 04:50:11 +00004125
4126 def testMakefileCloseSocketDestroy(self):
4127 refcount_before = sys.getrefcount(self.cli_conn)
Antoine Pitrou834bd812010-10-13 16:17:14 +00004128 self.read_file.close()
Gregory P. Smithde3369f2009-01-12 04:50:11 +00004129 refcount_after = sys.getrefcount(self.cli_conn)
4130 self.assertEqual(refcount_before - 1, refcount_after)
4131
4132 def _testMakefileCloseSocketDestroy(self):
4133 pass
4134
Antoine Pitrou98b46702010-09-18 22:59:00 +00004135 # Non-blocking ops
Antoine Pitrou834bd812010-10-13 16:17:14 +00004136 # NOTE: to set `read_file` as non-blocking, we must call
Antoine Pitrou98b46702010-09-18 22:59:00 +00004137 # `cli_conn.setblocking` and vice-versa (see setUp / clientSetUp).
4138
4139 def testSmallReadNonBlocking(self):
4140 self.cli_conn.setblocking(False)
Antoine Pitrou834bd812010-10-13 16:17:14 +00004141 self.assertEqual(self.read_file.readinto(bytearray(10)), None)
4142 self.assertEqual(self.read_file.read(len(self.read_msg) - 3), None)
Antoine Pitrou98b46702010-09-18 22:59:00 +00004143 self.evt1.set()
4144 self.evt2.wait(1.0)
Antoine Pitrou834bd812010-10-13 16:17:14 +00004145 first_seg = self.read_file.read(len(self.read_msg) - 3)
Antoine Pitrou43bf0452011-04-04 01:21:37 +02004146 if first_seg is None:
4147 # Data not arrived (can happen under Windows), wait a bit
4148 time.sleep(0.5)
4149 first_seg = self.read_file.read(len(self.read_msg) - 3)
Antoine Pitrou98b46702010-09-18 22:59:00 +00004150 buf = bytearray(10)
Antoine Pitrou834bd812010-10-13 16:17:14 +00004151 n = self.read_file.readinto(buf)
Antoine Pitrou98b46702010-09-18 22:59:00 +00004152 self.assertEqual(n, 3)
4153 msg = first_seg + buf[:n]
Antoine Pitrou834bd812010-10-13 16:17:14 +00004154 self.assertEqual(msg, self.read_msg)
4155 self.assertEqual(self.read_file.readinto(bytearray(16)), None)
4156 self.assertEqual(self.read_file.read(1), None)
Antoine Pitrou98b46702010-09-18 22:59:00 +00004157
4158 def _testSmallReadNonBlocking(self):
4159 self.evt1.wait(1.0)
Antoine Pitrou834bd812010-10-13 16:17:14 +00004160 self.write_file.write(self.write_msg)
4161 self.write_file.flush()
Antoine Pitrou98b46702010-09-18 22:59:00 +00004162 self.evt2.set()
4163 # Avoid cloding the socket before the server test has finished,
4164 # otherwise system recv() will return 0 instead of EWOULDBLOCK.
4165 self.serv_finished.wait(5.0)
4166
4167 def testWriteNonBlocking(self):
4168 self.cli_finished.wait(5.0)
4169 # The client thread can't skip directly - the SkipTest exception
4170 # would appear as a failure.
4171 if self.serv_skipped:
4172 self.skipTest(self.serv_skipped)
4173
4174 def _testWriteNonBlocking(self):
4175 self.serv_skipped = None
4176 self.serv_conn.setblocking(False)
4177 # Try to saturate the socket buffer pipe with repeated large writes.
Charles-François Natali5fd26422013-08-29 19:01:40 +02004178 BIG = b"x" * support.SOCK_MAX_SIZE
Antoine Pitrou98b46702010-09-18 22:59:00 +00004179 LIMIT = 10
4180 # The first write() succeeds since a chunk of data can be buffered
Antoine Pitrou834bd812010-10-13 16:17:14 +00004181 n = self.write_file.write(BIG)
Antoine Pitrou98b46702010-09-18 22:59:00 +00004182 self.assertGreater(n, 0)
4183 for i in range(LIMIT):
Antoine Pitrou834bd812010-10-13 16:17:14 +00004184 n = self.write_file.write(BIG)
Antoine Pitrou98b46702010-09-18 22:59:00 +00004185 if n is None:
4186 # Succeeded
4187 break
4188 self.assertGreater(n, 0)
4189 else:
4190 # Let us know that this test didn't manage to establish
4191 # the expected conditions. This is not a failure in itself but,
4192 # if it happens repeatedly, the test should be fixed.
4193 self.serv_skipped = "failed to saturate the socket buffer"
4194
Gregory P. Smithde3369f2009-01-12 04:50:11 +00004195
Guido van Rossum8c943832002-08-08 01:00:28 +00004196class LineBufferedFileObjectClassTestCase(FileObjectClassTestCase):
4197
4198 bufsize = 1 # Default-buffered for reading; line-buffered for writing
4199
4200
4201class SmallBufferedFileObjectClassTestCase(FileObjectClassTestCase):
4202
4203 bufsize = 2 # Exercise the buffering code
Guido van Rossume9f66142002-08-07 15:46:19 +00004204
Thomas Woutersb2137042007-02-01 18:02:27 +00004205
Antoine Pitrou834bd812010-10-13 16:17:14 +00004206class UnicodeReadFileObjectClassTestCase(FileObjectClassTestCase):
4207 """Tests for socket.makefile() in text mode (rather than binary)"""
4208
4209 read_mode = 'r'
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00004210 read_msg = MSG.decode('utf-8')
Antoine Pitrou834bd812010-10-13 16:17:14 +00004211 write_mode = 'wb'
4212 write_msg = MSG
4213 newline = ''
4214
4215
4216class UnicodeWriteFileObjectClassTestCase(FileObjectClassTestCase):
4217 """Tests for socket.makefile() in text mode (rather than binary)"""
4218
4219 read_mode = 'rb'
4220 read_msg = MSG
4221 write_mode = 'w'
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00004222 write_msg = MSG.decode('utf-8')
Antoine Pitrou834bd812010-10-13 16:17:14 +00004223 newline = ''
4224
4225
4226class UnicodeReadWriteFileObjectClassTestCase(FileObjectClassTestCase):
4227 """Tests for socket.makefile() in text mode (rather than binary)"""
4228
4229 read_mode = 'r'
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00004230 read_msg = MSG.decode('utf-8')
Antoine Pitrou834bd812010-10-13 16:17:14 +00004231 write_mode = 'w'
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00004232 write_msg = MSG.decode('utf-8')
Antoine Pitrou834bd812010-10-13 16:17:14 +00004233 newline = ''
4234
4235
Guido van Rossumd8faa362007-04-27 19:54:29 +00004236class NetworkConnectionTest(object):
4237 """Prove network connection."""
Guido van Rossum7d0a8262007-05-21 23:13:11 +00004238
Guido van Rossumd8faa362007-04-27 19:54:29 +00004239 def clientSetUp(self):
Christian Heimes5e696852008-04-09 08:37:03 +00004240 # We're inherited below by BasicTCPTest2, which also inherits
4241 # BasicTCPTest, which defines self.port referenced below.
4242 self.cli = socket.create_connection((HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +00004243 self.serv_conn = self.cli
4244
4245class BasicTCPTest2(NetworkConnectionTest, BasicTCPTest):
4246 """Tests that NetworkConnection does not break existing TCP functionality.
4247 """
4248
4249class NetworkConnectionNoServer(unittest.TestCase):
Guido van Rossum7d0a8262007-05-21 23:13:11 +00004250
Antoine Pitrou4b92b5f2010-09-07 21:05:49 +00004251 class MockSocket(socket.socket):
4252 def connect(self, *args):
4253 raise socket.timeout('timed out')
4254
4255 @contextlib.contextmanager
4256 def mocked_socket_module(self):
4257 """Return a socket which times out on connect"""
4258 old_socket = socket.socket
4259 socket.socket = self.MockSocket
4260 try:
4261 yield
4262 finally:
4263 socket.socket = old_socket
4264
4265 def test_connect(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00004266 port = support.find_unused_port()
Antoine Pitrou4b92b5f2010-09-07 21:05:49 +00004267 cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Brian Curtin21ebbb72010-11-02 02:07:09 +00004268 self.addCleanup(cli.close)
Andrew Svetlov0832af62012-12-18 23:10:48 +02004269 with self.assertRaises(OSError) as cm:
Antoine Pitrou4b92b5f2010-09-07 21:05:49 +00004270 cli.connect((HOST, port))
4271 self.assertEqual(cm.exception.errno, errno.ECONNREFUSED)
4272
4273 def test_create_connection(self):
4274 # Issue #9792: errors raised by create_connection() should have
4275 # a proper errno attribute.
4276 port = support.find_unused_port()
Andrew Svetlov0832af62012-12-18 23:10:48 +02004277 with self.assertRaises(OSError) as cm:
Antoine Pitrou4b92b5f2010-09-07 21:05:49 +00004278 socket.create_connection((HOST, port))
Trent Nelson45bb6132012-10-17 06:15:15 -04004279
4280 # Issue #16257: create_connection() calls getaddrinfo() against
4281 # 'localhost'. This may result in an IPV6 addr being returned
4282 # as well as an IPV4 one:
4283 # >>> socket.getaddrinfo('localhost', port, 0, SOCK_STREAM)
4284 # >>> [(2, 2, 0, '', ('127.0.0.1', 41230)),
4285 # (26, 2, 0, '', ('::1', 41230, 0, 0))]
4286 #
4287 # create_connection() enumerates through all the addresses returned
4288 # and if it doesn't successfully bind to any of them, it propagates
4289 # the last exception it encountered.
4290 #
4291 # On Solaris, ENETUNREACH is returned in this circumstance instead
4292 # of ECONNREFUSED. So, if that errno exists, add it to our list of
4293 # expected errnos.
4294 expected_errnos = [ errno.ECONNREFUSED, ]
4295 if hasattr(errno, 'ENETUNREACH'):
4296 expected_errnos.append(errno.ENETUNREACH)
4297
4298 self.assertIn(cm.exception.errno, expected_errnos)
Antoine Pitrou4b92b5f2010-09-07 21:05:49 +00004299
4300 def test_create_connection_timeout(self):
4301 # Issue #9792: create_connection() should not recast timeout errors
4302 # as generic socket errors.
4303 with self.mocked_socket_module():
4304 with self.assertRaises(socket.timeout):
4305 socket.create_connection((HOST, 1234))
4306
Guido van Rossumd8faa362007-04-27 19:54:29 +00004307
Victor Stinner45df8202010-04-28 22:31:17 +00004308@unittest.skipUnless(thread, 'Threading required for this test.')
Guido van Rossumd8faa362007-04-27 19:54:29 +00004309class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest):
4310
4311 def __init__(self, methodName='runTest'):
4312 SocketTCPTest.__init__(self, methodName=methodName)
4313 ThreadableTest.__init__(self)
4314
4315 def clientSetUp(self):
Gregory P. Smithb4066372010-01-03 03:28:29 +00004316 self.source_port = support.find_unused_port()
Guido van Rossumd8faa362007-04-27 19:54:29 +00004317
4318 def clientTearDown(self):
4319 self.cli.close()
4320 self.cli = None
4321 ThreadableTest.clientTearDown(self)
4322
4323 def _justAccept(self):
4324 conn, addr = self.serv.accept()
Brian Curtin21ebbb72010-11-02 02:07:09 +00004325 conn.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +00004326
4327 testFamily = _justAccept
4328 def _testFamily(self):
Christian Heimes5e696852008-04-09 08:37:03 +00004329 self.cli = socket.create_connection((HOST, self.port), timeout=30)
Brian Curtin21ebbb72010-11-02 02:07:09 +00004330 self.addCleanup(self.cli.close)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004331 self.assertEqual(self.cli.family, 2)
4332
Gregory P. Smitha81d8812010-01-03 15:09:32 +00004333 testSourceAddress = _justAccept
4334 def _testSourceAddress(self):
Gregory P. Smithb4066372010-01-03 03:28:29 +00004335 self.cli = socket.create_connection((HOST, self.port), timeout=30,
4336 source_address=('', self.source_port))
Brian Curtin21ebbb72010-11-02 02:07:09 +00004337 self.addCleanup(self.cli.close)
Gregory P. Smithb4066372010-01-03 03:28:29 +00004338 self.assertEqual(self.cli.getsockname()[1], self.source_port)
Gregory P. Smitha81d8812010-01-03 15:09:32 +00004339 # The port number being used is sufficient to show that the bind()
4340 # call happened.
Gregory P. Smithb4066372010-01-03 03:28:29 +00004341
Guido van Rossumd8faa362007-04-27 19:54:29 +00004342 testTimeoutDefault = _justAccept
4343 def _testTimeoutDefault(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +00004344 # passing no explicit timeout uses socket's global default
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00004345 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +00004346 socket.setdefaulttimeout(42)
4347 try:
4348 self.cli = socket.create_connection((HOST, self.port))
Brian Curtin21ebbb72010-11-02 02:07:09 +00004349 self.addCleanup(self.cli.close)
Georg Brandlf78e02b2008-06-10 17:40:04 +00004350 finally:
4351 socket.setdefaulttimeout(None)
Ezio Melottib3aedd42010-11-20 19:04:17 +00004352 self.assertEqual(self.cli.gettimeout(), 42)
Georg Brandlf78e02b2008-06-10 17:40:04 +00004353
4354 testTimeoutNone = _justAccept
4355 def _testTimeoutNone(self):
4356 # None timeout means the same as sock.settimeout(None)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00004357 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +00004358 socket.setdefaulttimeout(30)
4359 try:
4360 self.cli = socket.create_connection((HOST, self.port), timeout=None)
Brian Curtin21ebbb72010-11-02 02:07:09 +00004361 self.addCleanup(self.cli.close)
Georg Brandlf78e02b2008-06-10 17:40:04 +00004362 finally:
4363 socket.setdefaulttimeout(None)
4364 self.assertEqual(self.cli.gettimeout(), None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004365
4366 testTimeoutValueNamed = _justAccept
4367 def _testTimeoutValueNamed(self):
Christian Heimes5e696852008-04-09 08:37:03 +00004368 self.cli = socket.create_connection((HOST, self.port), timeout=30)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004369 self.assertEqual(self.cli.gettimeout(), 30)
4370
4371 testTimeoutValueNonamed = _justAccept
4372 def _testTimeoutValueNonamed(self):
Christian Heimes5e696852008-04-09 08:37:03 +00004373 self.cli = socket.create_connection((HOST, self.port), 30)
Brian Curtin21ebbb72010-11-02 02:07:09 +00004374 self.addCleanup(self.cli.close)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004375 self.assertEqual(self.cli.gettimeout(), 30)
4376
Victor Stinner45df8202010-04-28 22:31:17 +00004377@unittest.skipUnless(thread, 'Threading required for this test.')
Guido van Rossumd8faa362007-04-27 19:54:29 +00004378class NetworkConnectionBehaviourTest(SocketTCPTest, ThreadableTest):
4379
4380 def __init__(self, methodName='runTest'):
4381 SocketTCPTest.__init__(self, methodName=methodName)
4382 ThreadableTest.__init__(self)
4383
4384 def clientSetUp(self):
4385 pass
4386
4387 def clientTearDown(self):
4388 self.cli.close()
4389 self.cli = None
4390 ThreadableTest.clientTearDown(self)
4391
4392 def testInsideTimeout(self):
4393 conn, addr = self.serv.accept()
Brian Curtin21ebbb72010-11-02 02:07:09 +00004394 self.addCleanup(conn.close)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004395 time.sleep(3)
Guido van Rossum7d0a8262007-05-21 23:13:11 +00004396 conn.send(b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +00004397 testOutsideTimeout = testInsideTimeout
4398
4399 def _testInsideTimeout(self):
Christian Heimes5e696852008-04-09 08:37:03 +00004400 self.cli = sock = socket.create_connection((HOST, self.port))
Guido van Rossumd8faa362007-04-27 19:54:29 +00004401 data = sock.recv(5)
Guido van Rossum7d0a8262007-05-21 23:13:11 +00004402 self.assertEqual(data, b"done!")
Guido van Rossumd8faa362007-04-27 19:54:29 +00004403
4404 def _testOutsideTimeout(self):
Christian Heimes5e696852008-04-09 08:37:03 +00004405 self.cli = sock = socket.create_connection((HOST, self.port), timeout=1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00004406 self.assertRaises(socket.timeout, lambda: sock.recv(5))
Guido van Rossumd8faa362007-04-27 19:54:29 +00004407
4408
Raymond Hettinger11a35f52003-06-29 04:40:22 +00004409class TCPTimeoutTest(SocketTCPTest):
4410
4411 def testTCPTimeout(self):
4412 def raise_timeout(*args, **kwargs):
4413 self.serv.settimeout(1.0)
4414 self.serv.accept()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00004415 self.assertRaises(socket.timeout, raise_timeout,
Raymond Hettinger11a35f52003-06-29 04:40:22 +00004416 "Error generating a timeout exception (TCP)")
4417
4418 def testTimeoutZero(self):
4419 ok = False
4420 try:
4421 self.serv.settimeout(0.0)
4422 foo = self.serv.accept()
4423 except socket.timeout:
4424 self.fail("caught timeout instead of error (TCP)")
Andrew Svetlov0832af62012-12-18 23:10:48 +02004425 except OSError:
Raymond Hettinger11a35f52003-06-29 04:40:22 +00004426 ok = True
4427 except:
4428 self.fail("caught unexpected exception (TCP)")
4429 if not ok:
4430 self.fail("accept() returned success when we did not expect it")
4431
Serhiy Storchaka43767632013-11-03 21:31:38 +02004432 @unittest.skipUnless(hasattr(signal, 'alarm'),
4433 'test needs signal.alarm()')
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004434 def testInterruptedTimeout(self):
4435 # XXX I don't know how to do this test on MSWindows or any other
4436 # plaform that doesn't support signal.alarm() or os.kill(), though
4437 # the bug should have existed on all platforms.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004438 self.serv.settimeout(5.0) # must be longer than alarm
4439 class Alarm(Exception):
4440 pass
4441 def alarm_handler(signal, frame):
4442 raise Alarm
4443 old_alarm = signal.signal(signal.SIGALRM, alarm_handler)
4444 try:
4445 signal.alarm(2) # POSIX allows alarm to be up to 1 second early
4446 try:
4447 foo = self.serv.accept()
4448 except socket.timeout:
4449 self.fail("caught timeout instead of Alarm")
4450 except Alarm:
4451 pass
4452 except:
Christian Heimesbbe741d2008-03-28 10:53:29 +00004453 self.fail("caught other exception instead of Alarm:"
4454 " %s(%s):\n%s" %
4455 (sys.exc_info()[:2] + (traceback.format_exc(),)))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004456 else:
4457 self.fail("nothing caught")
Christian Heimesbbe741d2008-03-28 10:53:29 +00004458 finally:
4459 signal.alarm(0) # shut off alarm
Thomas Wouters0e3f5912006-08-11 14:57:12 +00004460 except Alarm:
4461 self.fail("got Alarm in wrong place")
4462 finally:
4463 # no alarm can be pending. Safe to restore old handler.
4464 signal.signal(signal.SIGALRM, old_alarm)
4465
Ezio Melotti7f78ddc2011-11-18 18:33:14 +02004466class UDPTimeoutTest(SocketUDPTest):
Raymond Hettinger11a35f52003-06-29 04:40:22 +00004467
4468 def testUDPTimeout(self):
4469 def raise_timeout(*args, **kwargs):
4470 self.serv.settimeout(1.0)
4471 self.serv.recv(1024)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00004472 self.assertRaises(socket.timeout, raise_timeout,
Raymond Hettinger11a35f52003-06-29 04:40:22 +00004473 "Error generating a timeout exception (UDP)")
4474
4475 def testTimeoutZero(self):
4476 ok = False
4477 try:
4478 self.serv.settimeout(0.0)
4479 foo = self.serv.recv(1024)
4480 except socket.timeout:
4481 self.fail("caught timeout instead of error (UDP)")
Andrew Svetlov0832af62012-12-18 23:10:48 +02004482 except OSError:
Raymond Hettinger11a35f52003-06-29 04:40:22 +00004483 ok = True
4484 except:
4485 self.fail("caught unexpected exception (UDP)")
4486 if not ok:
4487 self.fail("recv() returned success when we did not expect it")
4488
4489class TestExceptions(unittest.TestCase):
4490
4491 def testExceptionTree(self):
Andrew Svetlov0832af62012-12-18 23:10:48 +02004492 self.assertTrue(issubclass(OSError, Exception))
4493 self.assertTrue(issubclass(socket.herror, OSError))
4494 self.assertTrue(issubclass(socket.gaierror, OSError))
4495 self.assertTrue(issubclass(socket.timeout, OSError))
Raymond Hettinger11a35f52003-06-29 04:40:22 +00004496
Serhiy Storchaka43767632013-11-03 21:31:38 +02004497@unittest.skipUnless(sys.platform == 'linux', 'Linux specific test')
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004498class TestLinuxAbstractNamespace(unittest.TestCase):
4499
4500 UNIX_PATH_MAX = 108
4501
4502 def testLinuxAbstractNamespace(self):
Charles-François Natalib10c71d2013-05-21 10:45:46 +02004503 address = b"\x00python-test-hello\x00\xff"
Victor Stinner1d5eb342011-01-03 14:30:46 +00004504 with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s1:
4505 s1.bind(address)
Charles-François Natali6e204602014-07-23 19:28:13 +01004506 s1.listen()
Victor Stinner1d5eb342011-01-03 14:30:46 +00004507 with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s2:
4508 s2.connect(s1.getsockname())
4509 with s1.accept()[0] as s3:
4510 self.assertEqual(s1.getsockname(), address)
4511 self.assertEqual(s2.getpeername(), address)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004512
4513 def testMaxName(self):
Charles-François Natalib10c71d2013-05-21 10:45:46 +02004514 address = b"\x00" + b"h" * (self.UNIX_PATH_MAX - 1)
Victor Stinner1d5eb342011-01-03 14:30:46 +00004515 with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
4516 s.bind(address)
4517 self.assertEqual(s.getsockname(), address)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004518
4519 def testNameOverflow(self):
4520 address = "\x00" + "h" * self.UNIX_PATH_MAX
Victor Stinner1d5eb342011-01-03 14:30:46 +00004521 with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
Andrew Svetlov0832af62012-12-18 23:10:48 +02004522 self.assertRaises(OSError, s.bind, address)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004523
Charles-François Natalib10c71d2013-05-21 10:45:46 +02004524 def testStrName(self):
4525 # Check that an abstract name can be passed as a string.
Antoine Pitrou6ec29e22011-12-16 14:46:36 +01004526 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
4527 try:
Charles-François Natalib10c71d2013-05-21 10:45:46 +02004528 s.bind("\x00python\x00test\x00")
4529 self.assertEqual(s.getsockname(), b"\x00python\x00test\x00")
Antoine Pitrou6ec29e22011-12-16 14:46:36 +01004530 finally:
4531 s.close()
4532
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004533 def testBytearrayName(self):
4534 # Check that an abstract name can be passed as a bytearray.
4535 with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
4536 s.bind(bytearray(b"\x00python\x00test\x00"))
4537 self.assertEqual(s.getsockname(), b"\x00python\x00test\x00")
4538
Serhiy Storchaka43767632013-11-03 21:31:38 +02004539@unittest.skipUnless(hasattr(socket, 'AF_UNIX'), 'test needs socket.AF_UNIX')
Antoine Pitrou6ec29e22011-12-16 14:46:36 +01004540class TestUnixDomain(unittest.TestCase):
4541
4542 def setUp(self):
4543 self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
4544
4545 def tearDown(self):
4546 self.sock.close()
4547
4548 def encoded(self, path):
4549 # Return the given path encoded in the file system encoding,
4550 # or skip the test if this is not possible.
4551 try:
4552 return os.fsencode(path)
4553 except UnicodeEncodeError:
4554 self.skipTest(
4555 "Pathname {0!a} cannot be represented in file "
4556 "system encoding {1!r}".format(
4557 path, sys.getfilesystemencoding()))
4558
Antoine Pitrou16374872011-12-16 15:04:12 +01004559 def bind(self, sock, path):
4560 # Bind the socket
4561 try:
4562 sock.bind(path)
4563 except OSError as e:
4564 if str(e) == "AF_UNIX path too long":
4565 self.skipTest(
Serhiy Storchakad65c9492015-11-02 14:10:23 +02004566 "Pathname {0!a} is too long to serve as an AF_UNIX path"
Antoine Pitrou16374872011-12-16 15:04:12 +01004567 .format(path))
4568 else:
4569 raise
4570
Antoine Pitrou6ec29e22011-12-16 14:46:36 +01004571 def testStrAddr(self):
4572 # Test binding to and retrieving a normal string pathname.
4573 path = os.path.abspath(support.TESTFN)
Antoine Pitrou16374872011-12-16 15:04:12 +01004574 self.bind(self.sock, path)
Antoine Pitrou6ec29e22011-12-16 14:46:36 +01004575 self.addCleanup(support.unlink, path)
4576 self.assertEqual(self.sock.getsockname(), path)
4577
4578 def testBytesAddr(self):
4579 # Test binding to a bytes pathname.
4580 path = os.path.abspath(support.TESTFN)
Antoine Pitrou16374872011-12-16 15:04:12 +01004581 self.bind(self.sock, self.encoded(path))
Antoine Pitrou6ec29e22011-12-16 14:46:36 +01004582 self.addCleanup(support.unlink, path)
4583 self.assertEqual(self.sock.getsockname(), path)
4584
4585 def testSurrogateescapeBind(self):
4586 # Test binding to a valid non-ASCII pathname, with the
4587 # non-ASCII bytes supplied using surrogateescape encoding.
4588 path = os.path.abspath(support.TESTFN_UNICODE)
4589 b = self.encoded(path)
Antoine Pitrou16374872011-12-16 15:04:12 +01004590 self.bind(self.sock, b.decode("ascii", "surrogateescape"))
Antoine Pitrou6ec29e22011-12-16 14:46:36 +01004591 self.addCleanup(support.unlink, path)
4592 self.assertEqual(self.sock.getsockname(), path)
4593
4594 def testUnencodableAddr(self):
4595 # Test binding to a pathname that cannot be encoded in the
4596 # file system encoding.
4597 if support.TESTFN_UNENCODABLE is None:
4598 self.skipTest("No unencodable filename available")
4599 path = os.path.abspath(support.TESTFN_UNENCODABLE)
Antoine Pitrou16374872011-12-16 15:04:12 +01004600 self.bind(self.sock, path)
Antoine Pitrou6ec29e22011-12-16 14:46:36 +01004601 self.addCleanup(support.unlink, path)
4602 self.assertEqual(self.sock.getsockname(), path)
Raymond Hettinger11a35f52003-06-29 04:40:22 +00004603
Victor Stinner45df8202010-04-28 22:31:17 +00004604@unittest.skipUnless(thread, 'Threading required for this test.')
Thomas Wouters477c8d52006-05-27 19:21:47 +00004605class BufferIOTest(SocketConnectedTest):
4606 """
4607 Test the buffer versions of socket.recv() and socket.send().
4608 """
4609 def __init__(self, methodName='runTest'):
4610 SocketConnectedTest.__init__(self, methodName=methodName)
4611
Antoine Pitrou25480782010-03-17 22:50:28 +00004612 def testRecvIntoArray(self):
Antoine Pitrou2f89aa62008-08-02 21:02:48 +00004613 buf = bytearray(1024)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00004614 nbytes = self.cli_conn.recv_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00004615 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00004616 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00004617 self.assertEqual(msg, MSG)
4618
Antoine Pitrou25480782010-03-17 22:50:28 +00004619 def _testRecvIntoArray(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00004620 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00004621 self.serv_conn.send(buf)
4622
Antoine Pitrou25480782010-03-17 22:50:28 +00004623 def testRecvIntoBytearray(self):
4624 buf = bytearray(1024)
4625 nbytes = self.cli_conn.recv_into(buf)
4626 self.assertEqual(nbytes, len(MSG))
4627 msg = buf[:len(MSG)]
4628 self.assertEqual(msg, MSG)
4629
4630 _testRecvIntoBytearray = _testRecvIntoArray
4631
4632 def testRecvIntoMemoryview(self):
4633 buf = bytearray(1024)
4634 nbytes = self.cli_conn.recv_into(memoryview(buf))
4635 self.assertEqual(nbytes, len(MSG))
4636 msg = buf[:len(MSG)]
4637 self.assertEqual(msg, MSG)
4638
4639 _testRecvIntoMemoryview = _testRecvIntoArray
4640
4641 def testRecvFromIntoArray(self):
Antoine Pitrou2f89aa62008-08-02 21:02:48 +00004642 buf = bytearray(1024)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00004643 nbytes, addr = self.cli_conn.recvfrom_into(buf)
Thomas Wouters477c8d52006-05-27 19:21:47 +00004644 self.assertEqual(nbytes, len(MSG))
Guido van Rossum7d0a8262007-05-21 23:13:11 +00004645 msg = buf[:len(MSG)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00004646 self.assertEqual(msg, MSG)
4647
Antoine Pitrou25480782010-03-17 22:50:28 +00004648 def _testRecvFromIntoArray(self):
Guido van Rossumb5b22702007-05-18 18:55:53 +00004649 buf = bytes(MSG)
Thomas Wouters477c8d52006-05-27 19:21:47 +00004650 self.serv_conn.send(buf)
4651
Antoine Pitrou25480782010-03-17 22:50:28 +00004652 def testRecvFromIntoBytearray(self):
4653 buf = bytearray(1024)
4654 nbytes, addr = self.cli_conn.recvfrom_into(buf)
4655 self.assertEqual(nbytes, len(MSG))
4656 msg = buf[:len(MSG)]
4657 self.assertEqual(msg, MSG)
4658
4659 _testRecvFromIntoBytearray = _testRecvFromIntoArray
4660
4661 def testRecvFromIntoMemoryview(self):
4662 buf = bytearray(1024)
4663 nbytes, addr = self.cli_conn.recvfrom_into(memoryview(buf))
4664 self.assertEqual(nbytes, len(MSG))
4665 msg = buf[:len(MSG)]
4666 self.assertEqual(msg, MSG)
4667
4668 _testRecvFromIntoMemoryview = _testRecvFromIntoArray
4669
Benjamin Petersonc6b37e22014-01-13 23:14:42 -05004670 def testRecvFromIntoSmallBuffer(self):
4671 # See issue #20246.
4672 buf = bytearray(8)
4673 self.assertRaises(ValueError, self.cli_conn.recvfrom_into, buf, 1024)
4674
4675 def _testRecvFromIntoSmallBuffer(self):
Stefan Krah6b2e5592014-01-21 22:58:40 +01004676 self.serv_conn.send(MSG)
Benjamin Petersonc6b37e22014-01-13 23:14:42 -05004677
Benjamin Petersonbd1d12e2014-01-14 00:27:42 -05004678 def testRecvFromIntoEmptyBuffer(self):
4679 buf = bytearray()
4680 self.cli_conn.recvfrom_into(buf)
4681 self.cli_conn.recvfrom_into(buf, 0)
4682
4683 _testRecvFromIntoEmptyBuffer = _testRecvFromIntoArray
4684
Christian Heimes043d6f62008-01-07 17:19:16 +00004685
4686TIPC_STYPE = 2000
4687TIPC_LOWER = 200
4688TIPC_UPPER = 210
4689
4690def isTipcAvailable():
4691 """Check if the TIPC module is loaded
4692
4693 The TIPC module is not loaded automatically on Ubuntu and probably
4694 other Linux distros.
4695 """
4696 if not hasattr(socket, "AF_TIPC"):
4697 return False
4698 if not os.path.isfile("/proc/modules"):
4699 return False
4700 with open("/proc/modules") as f:
4701 for line in f:
4702 if line.startswith("tipc "):
4703 return True
Christian Heimes043d6f62008-01-07 17:19:16 +00004704 return False
4705
Serhiy Storchaka43767632013-11-03 21:31:38 +02004706@unittest.skipUnless(isTipcAvailable(),
4707 "TIPC module is not loaded, please 'sudo modprobe tipc'")
Antoine Pitrou86aed0b2011-10-02 23:33:19 +02004708class TIPCTest(unittest.TestCase):
Christian Heimes043d6f62008-01-07 17:19:16 +00004709 def testRDM(self):
4710 srv = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
4711 cli = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
Antoine Pitrou86aed0b2011-10-02 23:33:19 +02004712 self.addCleanup(srv.close)
4713 self.addCleanup(cli.close)
Christian Heimes043d6f62008-01-07 17:19:16 +00004714
4715 srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
4716 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
4717 TIPC_LOWER, TIPC_UPPER)
4718 srv.bind(srvaddr)
4719
4720 sendaddr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
4721 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
4722 cli.sendto(MSG, sendaddr)
4723
4724 msg, recvaddr = srv.recvfrom(1024)
4725
4726 self.assertEqual(cli.getsockname(), recvaddr)
4727 self.assertEqual(msg, MSG)
4728
4729
Serhiy Storchaka43767632013-11-03 21:31:38 +02004730@unittest.skipUnless(isTipcAvailable(),
4731 "TIPC module is not loaded, please 'sudo modprobe tipc'")
Antoine Pitrou86aed0b2011-10-02 23:33:19 +02004732class TIPCThreadableTest(unittest.TestCase, ThreadableTest):
Christian Heimes043d6f62008-01-07 17:19:16 +00004733 def __init__(self, methodName = 'runTest'):
4734 unittest.TestCase.__init__(self, methodName = methodName)
4735 ThreadableTest.__init__(self)
4736
4737 def setUp(self):
4738 self.srv = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
Antoine Pitrou86aed0b2011-10-02 23:33:19 +02004739 self.addCleanup(self.srv.close)
Christian Heimes043d6f62008-01-07 17:19:16 +00004740 self.srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
4741 srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
4742 TIPC_LOWER, TIPC_UPPER)
4743 self.srv.bind(srvaddr)
Charles-François Natali6e204602014-07-23 19:28:13 +01004744 self.srv.listen()
Christian Heimes043d6f62008-01-07 17:19:16 +00004745 self.serverExplicitReady()
4746 self.conn, self.connaddr = self.srv.accept()
Antoine Pitrou86aed0b2011-10-02 23:33:19 +02004747 self.addCleanup(self.conn.close)
Christian Heimes043d6f62008-01-07 17:19:16 +00004748
4749 def clientSetUp(self):
Martin Pantera90a4a92016-05-30 04:04:50 +00004750 # There is a hittable race between serverExplicitReady() and the
Christian Heimes043d6f62008-01-07 17:19:16 +00004751 # accept() call; sleep a little while to avoid it, otherwise
4752 # we could get an exception
4753 time.sleep(0.1)
4754 self.cli = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
Antoine Pitrou86aed0b2011-10-02 23:33:19 +02004755 self.addCleanup(self.cli.close)
Christian Heimes043d6f62008-01-07 17:19:16 +00004756 addr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
4757 TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
4758 self.cli.connect(addr)
4759 self.cliaddr = self.cli.getsockname()
4760
4761 def testStream(self):
4762 msg = self.conn.recv(1024)
4763 self.assertEqual(msg, MSG)
4764 self.assertEqual(self.cliaddr, self.connaddr)
4765
4766 def _testStream(self):
4767 self.cli.send(MSG)
4768 self.cli.close()
4769
4770
Giampaolo Rodolàb383dbb2010-09-08 22:44:12 +00004771@unittest.skipUnless(thread, 'Threading required for this test.')
4772class ContextManagersTest(ThreadedTCPSocketTest):
4773
4774 def _testSocketClass(self):
4775 # base test
4776 with socket.socket() as sock:
4777 self.assertFalse(sock._closed)
4778 self.assertTrue(sock._closed)
4779 # close inside with block
4780 with socket.socket() as sock:
4781 sock.close()
4782 self.assertTrue(sock._closed)
4783 # exception inside with block
4784 with socket.socket() as sock:
Andrew Svetlov0832af62012-12-18 23:10:48 +02004785 self.assertRaises(OSError, sock.sendall, b'foo')
Giampaolo Rodolàb383dbb2010-09-08 22:44:12 +00004786 self.assertTrue(sock._closed)
4787
4788 def testCreateConnectionBase(self):
4789 conn, addr = self.serv.accept()
Brian Curtin21ebbb72010-11-02 02:07:09 +00004790 self.addCleanup(conn.close)
Giampaolo Rodolàb383dbb2010-09-08 22:44:12 +00004791 data = conn.recv(1024)
4792 conn.sendall(data)
4793
4794 def _testCreateConnectionBase(self):
4795 address = self.serv.getsockname()
4796 with socket.create_connection(address) as sock:
4797 self.assertFalse(sock._closed)
4798 sock.sendall(b'foo')
4799 self.assertEqual(sock.recv(1024), b'foo')
4800 self.assertTrue(sock._closed)
4801
4802 def testCreateConnectionClose(self):
4803 conn, addr = self.serv.accept()
Brian Curtin21ebbb72010-11-02 02:07:09 +00004804 self.addCleanup(conn.close)
Giampaolo Rodolàb383dbb2010-09-08 22:44:12 +00004805 data = conn.recv(1024)
4806 conn.sendall(data)
4807
4808 def _testCreateConnectionClose(self):
4809 address = self.serv.getsockname()
4810 with socket.create_connection(address) as sock:
4811 sock.close()
4812 self.assertTrue(sock._closed)
Andrew Svetlov0832af62012-12-18 23:10:48 +02004813 self.assertRaises(OSError, sock.sendall, b'foo')
Giampaolo Rodolàb383dbb2010-09-08 22:44:12 +00004814
Antoine Pitrouacd0fda2010-10-23 17:01:44 +00004815
Victor Stinnerdaf45552013-08-28 00:53:59 +02004816class InheritanceTest(unittest.TestCase):
4817 @unittest.skipUnless(hasattr(socket, "SOCK_CLOEXEC"),
4818 "SOCK_CLOEXEC not defined")
Charles-François Natali239bb962011-06-03 12:55:15 +02004819 @support.requires_linux_version(2, 6, 28)
Antoine Pitroub1c54962010-10-14 15:05:38 +00004820 def test_SOCK_CLOEXEC(self):
Victor Stinner1d5eb342011-01-03 14:30:46 +00004821 with socket.socket(socket.AF_INET,
4822 socket.SOCK_STREAM | socket.SOCK_CLOEXEC) as s:
4823 self.assertTrue(s.type & socket.SOCK_CLOEXEC)
Victor Stinnerd39dca92013-08-28 12:28:18 +02004824 self.assertFalse(s.get_inheritable())
Victor Stinnerdaf45552013-08-28 00:53:59 +02004825
4826 def test_default_inheritable(self):
4827 sock = socket.socket()
4828 with sock:
4829 self.assertEqual(sock.get_inheritable(), False)
4830
4831 def test_dup(self):
4832 sock = socket.socket()
4833 with sock:
4834 newsock = sock.dup()
4835 sock.close()
4836 with newsock:
4837 self.assertEqual(newsock.get_inheritable(), False)
4838
4839 def test_set_inheritable(self):
4840 sock = socket.socket()
4841 with sock:
4842 sock.set_inheritable(True)
4843 self.assertEqual(sock.get_inheritable(), True)
4844
4845 sock.set_inheritable(False)
4846 self.assertEqual(sock.get_inheritable(), False)
4847
Victor Stinner4f7a36f2013-09-08 14:14:38 +02004848 @unittest.skipIf(fcntl is None, "need fcntl")
4849 def test_get_inheritable_cloexec(self):
4850 sock = socket.socket()
4851 with sock:
4852 fd = sock.fileno()
4853 self.assertEqual(sock.get_inheritable(), False)
Victor Stinnera3c18d02013-09-08 11:53:09 +02004854
Victor Stinner4f7a36f2013-09-08 14:14:38 +02004855 # clear FD_CLOEXEC flag
4856 flags = fcntl.fcntl(fd, fcntl.F_GETFD)
4857 flags &= ~fcntl.FD_CLOEXEC
4858 fcntl.fcntl(fd, fcntl.F_SETFD, flags)
Victor Stinnera3c18d02013-09-08 11:53:09 +02004859
Victor Stinner4f7a36f2013-09-08 14:14:38 +02004860 self.assertEqual(sock.get_inheritable(), True)
Victor Stinnera3c18d02013-09-08 11:53:09 +02004861
Victor Stinner4f7a36f2013-09-08 14:14:38 +02004862 @unittest.skipIf(fcntl is None, "need fcntl")
4863 def test_set_inheritable_cloexec(self):
4864 sock = socket.socket()
4865 with sock:
4866 fd = sock.fileno()
4867 self.assertEqual(fcntl.fcntl(fd, fcntl.F_GETFD) & fcntl.FD_CLOEXEC,
4868 fcntl.FD_CLOEXEC)
Victor Stinnera3c18d02013-09-08 11:53:09 +02004869
Victor Stinner4f7a36f2013-09-08 14:14:38 +02004870 sock.set_inheritable(True)
4871 self.assertEqual(fcntl.fcntl(fd, fcntl.F_GETFD) & fcntl.FD_CLOEXEC,
4872 0)
Victor Stinnera3c18d02013-09-08 11:53:09 +02004873
4874
Victor Stinnerdaf45552013-08-28 00:53:59 +02004875 @unittest.skipUnless(hasattr(socket, "socketpair"),
4876 "need socket.socketpair()")
4877 def test_socketpair(self):
4878 s1, s2 = socket.socketpair()
4879 self.addCleanup(s1.close)
4880 self.addCleanup(s2.close)
4881 self.assertEqual(s1.get_inheritable(), False)
4882 self.assertEqual(s2.get_inheritable(), False)
Antoine Pitroub1c54962010-10-14 15:05:38 +00004883
4884
4885@unittest.skipUnless(hasattr(socket, "SOCK_NONBLOCK"),
4886 "SOCK_NONBLOCK not defined")
4887class NonblockConstantTest(unittest.TestCase):
4888 def checkNonblock(self, s, nonblock=True, timeout=0.0):
4889 if nonblock:
4890 self.assertTrue(s.type & socket.SOCK_NONBLOCK)
4891 self.assertEqual(s.gettimeout(), timeout)
4892 else:
4893 self.assertFalse(s.type & socket.SOCK_NONBLOCK)
4894 self.assertEqual(s.gettimeout(), None)
4895
Charles-François Natali239bb962011-06-03 12:55:15 +02004896 @support.requires_linux_version(2, 6, 28)
Antoine Pitroub1c54962010-10-14 15:05:38 +00004897 def test_SOCK_NONBLOCK(self):
4898 # a lot of it seems silly and redundant, but I wanted to test that
4899 # changing back and forth worked ok
Victor Stinner1d5eb342011-01-03 14:30:46 +00004900 with socket.socket(socket.AF_INET,
4901 socket.SOCK_STREAM | socket.SOCK_NONBLOCK) as s:
4902 self.checkNonblock(s)
4903 s.setblocking(1)
4904 self.checkNonblock(s, False)
4905 s.setblocking(0)
4906 self.checkNonblock(s)
4907 s.settimeout(None)
4908 self.checkNonblock(s, False)
4909 s.settimeout(2.0)
4910 self.checkNonblock(s, timeout=2.0)
4911 s.setblocking(1)
4912 self.checkNonblock(s, False)
Antoine Pitroub1c54962010-10-14 15:05:38 +00004913 # defaulttimeout
4914 t = socket.getdefaulttimeout()
4915 socket.setdefaulttimeout(0.0)
Victor Stinner1d5eb342011-01-03 14:30:46 +00004916 with socket.socket() as s:
4917 self.checkNonblock(s)
Antoine Pitroub1c54962010-10-14 15:05:38 +00004918 socket.setdefaulttimeout(None)
Victor Stinner1d5eb342011-01-03 14:30:46 +00004919 with socket.socket() as s:
4920 self.checkNonblock(s, False)
Antoine Pitroub1c54962010-10-14 15:05:38 +00004921 socket.setdefaulttimeout(2.0)
Victor Stinner1d5eb342011-01-03 14:30:46 +00004922 with socket.socket() as s:
4923 self.checkNonblock(s, timeout=2.0)
Antoine Pitroub1c54962010-10-14 15:05:38 +00004924 socket.setdefaulttimeout(None)
Victor Stinner1d5eb342011-01-03 14:30:46 +00004925 with socket.socket() as s:
4926 self.checkNonblock(s, False)
Antoine Pitroub1c54962010-10-14 15:05:38 +00004927 socket.setdefaulttimeout(t)
4928
Giampaolo Rodolàb383dbb2010-09-08 22:44:12 +00004929
Kristján Valur Jónsson10f383a2012-04-07 11:23:31 +00004930@unittest.skipUnless(os.name == "nt", "Windows specific")
4931@unittest.skipUnless(multiprocessing, "need multiprocessing")
4932class TestSocketSharing(SocketTCPTest):
4933 # This must be classmethod and not staticmethod or multiprocessing
4934 # won't be able to bootstrap it.
4935 @classmethod
4936 def remoteProcessServer(cls, q):
4937 # Recreate socket from shared data
4938 sdata = q.get()
4939 message = q.get()
4940
4941 s = socket.fromshare(sdata)
4942 s2, c = s.accept()
4943
4944 # Send the message
4945 s2.sendall(message)
4946 s2.close()
4947 s.close()
4948
4949 def testShare(self):
4950 # Transfer the listening server socket to another process
4951 # and service it from there.
4952
4953 # Create process:
4954 q = multiprocessing.Queue()
4955 p = multiprocessing.Process(target=self.remoteProcessServer, args=(q,))
4956 p.start()
4957
4958 # Get the shared socket data
4959 data = self.serv.share(p.pid)
4960
4961 # Pass the shared socket to the other process
4962 addr = self.serv.getsockname()
4963 self.serv.close()
4964 q.put(data)
4965
4966 # The data that the server will send us
4967 message = b"slapmahfro"
4968 q.put(message)
4969
4970 # Connect
4971 s = socket.create_connection(addr)
4972 # listen for the data
4973 m = []
4974 while True:
4975 data = s.recv(100)
4976 if not data:
4977 break
4978 m.append(data)
4979 s.close()
4980 received = b"".join(m)
4981 self.assertEqual(received, message)
4982 p.join()
4983
4984 def testShareLength(self):
4985 data = self.serv.share(os.getpid())
4986 self.assertRaises(ValueError, socket.fromshare, data[:-1])
4987 self.assertRaises(ValueError, socket.fromshare, data+b"foo")
4988
4989 def compareSockets(self, org, other):
4990 # socket sharing is expected to work only for blocking socket
Martin Panter46f50722016-05-26 05:35:26 +00004991 # since the internal python timeout value isn't transferred.
Kristján Valur Jónsson10f383a2012-04-07 11:23:31 +00004992 self.assertEqual(org.gettimeout(), None)
4993 self.assertEqual(org.gettimeout(), other.gettimeout())
4994
4995 self.assertEqual(org.family, other.family)
4996 self.assertEqual(org.type, other.type)
4997 # If the user specified "0" for proto, then
4998 # internally windows will have picked the correct value.
4999 # Python introspection on the socket however will still return
5000 # 0. For the shared socket, the python value is recreated
5001 # from the actual value, so it may not compare correctly.
5002 if org.proto != 0:
5003 self.assertEqual(org.proto, other.proto)
5004
5005 def testShareLocal(self):
5006 data = self.serv.share(os.getpid())
5007 s = socket.fromshare(data)
5008 try:
5009 self.compareSockets(self.serv, s)
5010 finally:
5011 s.close()
5012
5013 def testTypes(self):
5014 families = [socket.AF_INET, socket.AF_INET6]
5015 types = [socket.SOCK_STREAM, socket.SOCK_DGRAM]
5016 for f in families:
5017 for t in types:
Kristján Valur Jónsson52a11f12012-04-07 20:38:44 +00005018 try:
5019 source = socket.socket(f, t)
5020 except OSError:
5021 continue # This combination is not supported
Kristján Valur Jónsson10f383a2012-04-07 11:23:31 +00005022 try:
5023 data = source.share(os.getpid())
5024 shared = socket.fromshare(data)
5025 try:
5026 self.compareSockets(source, shared)
5027 finally:
5028 shared.close()
5029 finally:
5030 source.close()
5031
5032
Giampaolo Rodola'915d1412014-06-11 03:54:30 +02005033@unittest.skipUnless(thread, 'Threading required for this test.')
5034class SendfileUsingSendTest(ThreadedTCPSocketTest):
5035 """
5036 Test the send() implementation of socket.sendfile().
5037 """
5038
5039 FILESIZE = (10 * 1024 * 1024) # 10MB
5040 BUFSIZE = 8192
5041 FILEDATA = b""
5042 TIMEOUT = 2
5043
5044 @classmethod
5045 def setUpClass(cls):
5046 def chunks(total, step):
5047 assert total >= step
5048 while total > step:
5049 yield step
5050 total -= step
5051 if total:
5052 yield total
5053
5054 chunk = b"".join([random.choice(string.ascii_letters).encode()
5055 for i in range(cls.BUFSIZE)])
5056 with open(support.TESTFN, 'wb') as f:
5057 for csize in chunks(cls.FILESIZE, cls.BUFSIZE):
5058 f.write(chunk)
5059 with open(support.TESTFN, 'rb') as f:
5060 cls.FILEDATA = f.read()
5061 assert len(cls.FILEDATA) == cls.FILESIZE
5062
5063 @classmethod
5064 def tearDownClass(cls):
5065 support.unlink(support.TESTFN)
5066
5067 def accept_conn(self):
5068 self.serv.settimeout(self.TIMEOUT)
5069 conn, addr = self.serv.accept()
5070 conn.settimeout(self.TIMEOUT)
5071 self.addCleanup(conn.close)
5072 return conn
5073
5074 def recv_data(self, conn):
5075 received = []
5076 while True:
5077 chunk = conn.recv(self.BUFSIZE)
5078 if not chunk:
5079 break
5080 received.append(chunk)
5081 return b''.join(received)
5082
5083 def meth_from_sock(self, sock):
5084 # Depending on the mixin class being run return either send()
5085 # or sendfile() method implementation.
5086 return getattr(sock, "_sendfile_use_send")
5087
5088 # regular file
5089
5090 def _testRegularFile(self):
5091 address = self.serv.getsockname()
5092 file = open(support.TESTFN, 'rb')
5093 with socket.create_connection(address) as sock, file as file:
5094 meth = self.meth_from_sock(sock)
5095 sent = meth(file)
5096 self.assertEqual(sent, self.FILESIZE)
5097 self.assertEqual(file.tell(), self.FILESIZE)
5098
5099 def testRegularFile(self):
5100 conn = self.accept_conn()
5101 data = self.recv_data(conn)
5102 self.assertEqual(len(data), self.FILESIZE)
5103 self.assertEqual(data, self.FILEDATA)
5104
5105 # non regular file
5106
5107 def _testNonRegularFile(self):
5108 address = self.serv.getsockname()
5109 file = io.BytesIO(self.FILEDATA)
5110 with socket.create_connection(address) as sock, file as file:
5111 sent = sock.sendfile(file)
5112 self.assertEqual(sent, self.FILESIZE)
5113 self.assertEqual(file.tell(), self.FILESIZE)
5114 self.assertRaises(socket._GiveupOnSendfile,
5115 sock._sendfile_use_sendfile, file)
5116
5117 def testNonRegularFile(self):
5118 conn = self.accept_conn()
5119 data = self.recv_data(conn)
5120 self.assertEqual(len(data), self.FILESIZE)
5121 self.assertEqual(data, self.FILEDATA)
5122
5123 # empty file
5124
5125 def _testEmptyFileSend(self):
5126 address = self.serv.getsockname()
5127 filename = support.TESTFN + "2"
5128 with open(filename, 'wb'):
5129 self.addCleanup(support.unlink, filename)
5130 file = open(filename, 'rb')
5131 with socket.create_connection(address) as sock, file as file:
5132 meth = self.meth_from_sock(sock)
5133 sent = meth(file)
5134 self.assertEqual(sent, 0)
5135 self.assertEqual(file.tell(), 0)
5136
5137 def testEmptyFileSend(self):
5138 conn = self.accept_conn()
5139 data = self.recv_data(conn)
5140 self.assertEqual(data, b"")
5141
5142 # offset
5143
5144 def _testOffset(self):
5145 address = self.serv.getsockname()
5146 file = open(support.TESTFN, 'rb')
5147 with socket.create_connection(address) as sock, file as file:
5148 meth = self.meth_from_sock(sock)
5149 sent = meth(file, offset=5000)
5150 self.assertEqual(sent, self.FILESIZE - 5000)
5151 self.assertEqual(file.tell(), self.FILESIZE)
5152
5153 def testOffset(self):
5154 conn = self.accept_conn()
5155 data = self.recv_data(conn)
5156 self.assertEqual(len(data), self.FILESIZE - 5000)
5157 self.assertEqual(data, self.FILEDATA[5000:])
5158
5159 # count
5160
5161 def _testCount(self):
5162 address = self.serv.getsockname()
5163 file = open(support.TESTFN, 'rb')
5164 with socket.create_connection(address, timeout=2) as sock, file as file:
5165 count = 5000007
5166 meth = self.meth_from_sock(sock)
5167 sent = meth(file, count=count)
5168 self.assertEqual(sent, count)
5169 self.assertEqual(file.tell(), count)
5170
5171 def testCount(self):
5172 count = 5000007
5173 conn = self.accept_conn()
5174 data = self.recv_data(conn)
5175 self.assertEqual(len(data), count)
5176 self.assertEqual(data, self.FILEDATA[:count])
5177
5178 # count small
5179
5180 def _testCountSmall(self):
5181 address = self.serv.getsockname()
5182 file = open(support.TESTFN, 'rb')
5183 with socket.create_connection(address, timeout=2) as sock, file as file:
5184 count = 1
5185 meth = self.meth_from_sock(sock)
5186 sent = meth(file, count=count)
5187 self.assertEqual(sent, count)
5188 self.assertEqual(file.tell(), count)
5189
5190 def testCountSmall(self):
5191 count = 1
5192 conn = self.accept_conn()
5193 data = self.recv_data(conn)
5194 self.assertEqual(len(data), count)
5195 self.assertEqual(data, self.FILEDATA[:count])
5196
5197 # count + offset
5198
5199 def _testCountWithOffset(self):
5200 address = self.serv.getsockname()
5201 file = open(support.TESTFN, 'rb')
5202 with socket.create_connection(address, timeout=2) as sock, file as file:
5203 count = 100007
5204 meth = self.meth_from_sock(sock)
5205 sent = meth(file, offset=2007, count=count)
5206 self.assertEqual(sent, count)
5207 self.assertEqual(file.tell(), count + 2007)
5208
5209 def testCountWithOffset(self):
5210 count = 100007
5211 conn = self.accept_conn()
5212 data = self.recv_data(conn)
5213 self.assertEqual(len(data), count)
5214 self.assertEqual(data, self.FILEDATA[2007:count+2007])
5215
5216 # non blocking sockets are not supposed to work
5217
5218 def _testNonBlocking(self):
5219 address = self.serv.getsockname()
5220 file = open(support.TESTFN, 'rb')
5221 with socket.create_connection(address) as sock, file as file:
5222 sock.setblocking(False)
5223 meth = self.meth_from_sock(sock)
5224 self.assertRaises(ValueError, meth, file)
5225 self.assertRaises(ValueError, sock.sendfile, file)
5226
5227 def testNonBlocking(self):
5228 conn = self.accept_conn()
5229 if conn.recv(8192):
5230 self.fail('was not supposed to receive any data')
5231
5232 # timeout (non-triggered)
5233
5234 def _testWithTimeout(self):
5235 address = self.serv.getsockname()
5236 file = open(support.TESTFN, 'rb')
5237 with socket.create_connection(address, timeout=2) as sock, file as file:
5238 meth = self.meth_from_sock(sock)
5239 sent = meth(file)
5240 self.assertEqual(sent, self.FILESIZE)
5241
5242 def testWithTimeout(self):
5243 conn = self.accept_conn()
5244 data = self.recv_data(conn)
5245 self.assertEqual(len(data), self.FILESIZE)
5246 self.assertEqual(data, self.FILEDATA)
5247
5248 # timeout (triggered)
5249
5250 def _testWithTimeoutTriggeredSend(self):
5251 address = self.serv.getsockname()
5252 file = open(support.TESTFN, 'rb')
5253 with socket.create_connection(address, timeout=0.01) as sock, \
5254 file as file:
5255 meth = self.meth_from_sock(sock)
5256 self.assertRaises(socket.timeout, meth, file)
5257
5258 def testWithTimeoutTriggeredSend(self):
5259 conn = self.accept_conn()
5260 conn.recv(88192)
5261
5262 # errors
5263
5264 def _test_errors(self):
5265 pass
5266
5267 def test_errors(self):
5268 with open(support.TESTFN, 'rb') as file:
5269 with socket.socket(type=socket.SOCK_DGRAM) as s:
5270 meth = self.meth_from_sock(s)
5271 self.assertRaisesRegex(
5272 ValueError, "SOCK_STREAM", meth, file)
5273 with open(support.TESTFN, 'rt') as file:
5274 with socket.socket() as s:
5275 meth = self.meth_from_sock(s)
5276 self.assertRaisesRegex(
5277 ValueError, "binary mode", meth, file)
5278 with open(support.TESTFN, 'rb') as file:
5279 with socket.socket() as s:
5280 meth = self.meth_from_sock(s)
5281 self.assertRaisesRegex(TypeError, "positive integer",
5282 meth, file, count='2')
5283 self.assertRaisesRegex(TypeError, "positive integer",
5284 meth, file, count=0.1)
5285 self.assertRaisesRegex(ValueError, "positive integer",
5286 meth, file, count=0)
5287 self.assertRaisesRegex(ValueError, "positive integer",
5288 meth, file, count=-1)
5289
5290
5291@unittest.skipUnless(thread, 'Threading required for this test.')
5292@unittest.skipUnless(hasattr(os, "sendfile"),
5293 'os.sendfile() required for this test.')
5294class SendfileUsingSendfileTest(SendfileUsingSendTest):
5295 """
5296 Test the sendfile() implementation of socket.sendfile().
5297 """
5298 def meth_from_sock(self, sock):
5299 return getattr(sock, "_sendfile_use_sendfile")
5300
5301
Guido van Rossumb995eb72002-07-31 16:08:40 +00005302def test_main():
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005303 tests = [GeneralModuleTests, BasicTCPTest, TCPCloserTest, TCPTimeoutTest,
Ronald Oussoren94f25282010-05-05 19:11:21 +00005304 TestExceptions, BufferIOTest, BasicTCPTest2, BasicUDPTest, UDPTimeoutTest ]
Walter Dörwald21d3a322003-05-01 17:45:56 +00005305
5306 tests.extend([
5307 NonBlockingTCPTests,
5308 FileObjectClassTestCase,
5309 UnbufferedFileObjectClassTestCase,
5310 LineBufferedFileObjectClassTestCase,
Thomas Woutersb2137042007-02-01 18:02:27 +00005311 SmallBufferedFileObjectClassTestCase,
Antoine Pitrou834bd812010-10-13 16:17:14 +00005312 UnicodeReadFileObjectClassTestCase,
5313 UnicodeWriteFileObjectClassTestCase,
5314 UnicodeReadWriteFileObjectClassTestCase,
Guido van Rossumd8faa362007-04-27 19:54:29 +00005315 NetworkConnectionNoServer,
5316 NetworkConnectionAttributesTest,
5317 NetworkConnectionBehaviourTest,
Giampaolo Rodolàb383dbb2010-09-08 22:44:12 +00005318 ContextManagersTest,
Victor Stinnerdaf45552013-08-28 00:53:59 +02005319 InheritanceTest,
Antoine Pitroub1c54962010-10-14 15:05:38 +00005320 NonblockConstantTest
Walter Dörwald21d3a322003-05-01 17:45:56 +00005321 ])
Serhiy Storchaka43767632013-11-03 21:31:38 +02005322 tests.append(BasicSocketPairTest)
5323 tests.append(TestUnixDomain)
5324 tests.append(TestLinuxAbstractNamespace)
5325 tests.extend([TIPCTest, TIPCThreadableTest])
Charles-François Natali47413c12011-10-06 19:47:44 +02005326 tests.extend([BasicCANTest, CANTest])
Charles-François Natali10b8cf42011-11-10 19:21:37 +01005327 tests.extend([BasicRDSTest, RDSTest])
Nick Coghlan96fe56a2011-08-22 11:55:57 +10005328 tests.extend([
5329 CmsgMacroTests,
5330 SendmsgUDPTest,
5331 RecvmsgUDPTest,
5332 RecvmsgIntoUDPTest,
5333 SendmsgUDP6Test,
5334 RecvmsgUDP6Test,
5335 RecvmsgRFC3542AncillaryUDP6Test,
5336 RecvmsgIntoRFC3542AncillaryUDP6Test,
5337 RecvmsgIntoUDP6Test,
5338 SendmsgTCPTest,
5339 RecvmsgTCPTest,
5340 RecvmsgIntoTCPTest,
5341 SendmsgSCTPStreamTest,
5342 RecvmsgSCTPStreamTest,
5343 RecvmsgIntoSCTPStreamTest,
5344 SendmsgUnixStreamTest,
5345 RecvmsgUnixStreamTest,
5346 RecvmsgIntoUnixStreamTest,
5347 RecvmsgSCMRightsStreamTest,
5348 RecvmsgIntoSCMRightsStreamTest,
5349 # These are slow when setitimer() is not available
5350 InterruptedRecvTimeoutTest,
5351 InterruptedSendTimeoutTest,
Kristján Valur Jónsson10f383a2012-04-07 11:23:31 +00005352 TestSocketSharing,
Giampaolo Rodola'915d1412014-06-11 03:54:30 +02005353 SendfileUsingSendTest,
5354 SendfileUsingSendfileTest,
Nick Coghlan96fe56a2011-08-22 11:55:57 +10005355 ])
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005356
Benjamin Petersonee8712c2008-05-20 21:35:26 +00005357 thread_info = support.threading_setup()
5358 support.run_unittest(*tests)
5359 support.threading_cleanup(*thread_info)
Guido van Rossum24e4af82002-06-12 19:18:08 +00005360
5361if __name__ == "__main__":
Guido van Rossumb995eb72002-07-31 16:08:40 +00005362 test_main()