1 | n/a | import unittest |
---|
2 | n/a | from test import support |
---|
3 | n/a | |
---|
4 | n/a | import errno |
---|
5 | n/a | import io |
---|
6 | n/a | import itertools |
---|
7 | n/a | import socket |
---|
8 | n/a | import select |
---|
9 | n/a | import tempfile |
---|
10 | n/a | import time |
---|
11 | n/a | import traceback |
---|
12 | n/a | import queue |
---|
13 | n/a | import sys |
---|
14 | n/a | import os |
---|
15 | n/a | import array |
---|
16 | n/a | import contextlib |
---|
17 | n/a | from weakref import proxy |
---|
18 | n/a | import signal |
---|
19 | n/a | import math |
---|
20 | n/a | import pickle |
---|
21 | n/a | import struct |
---|
22 | n/a | import random |
---|
23 | n/a | import string |
---|
24 | n/a | try: |
---|
25 | n/a | import multiprocessing |
---|
26 | n/a | except ImportError: |
---|
27 | n/a | multiprocessing = False |
---|
28 | n/a | try: |
---|
29 | n/a | import fcntl |
---|
30 | n/a | except ImportError: |
---|
31 | n/a | fcntl = None |
---|
32 | n/a | |
---|
33 | n/a | HOST = support.HOST |
---|
34 | n/a | MSG = 'Michael Gilfix was here\u1234\r\n'.encode('utf-8') ## test unicode string and carriage return |
---|
35 | n/a | |
---|
36 | n/a | try: |
---|
37 | n/a | import _thread as thread |
---|
38 | n/a | import threading |
---|
39 | n/a | except ImportError: |
---|
40 | n/a | thread = None |
---|
41 | n/a | threading = None |
---|
42 | n/a | try: |
---|
43 | n/a | import _socket |
---|
44 | n/a | except ImportError: |
---|
45 | n/a | _socket = None |
---|
46 | n/a | |
---|
47 | n/a | |
---|
48 | n/a | def _have_socket_can(): |
---|
49 | n/a | """Check whether CAN sockets are supported on this host.""" |
---|
50 | n/a | try: |
---|
51 | n/a | s = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) |
---|
52 | n/a | except (AttributeError, OSError): |
---|
53 | n/a | return False |
---|
54 | n/a | else: |
---|
55 | n/a | s.close() |
---|
56 | n/a | return True |
---|
57 | n/a | |
---|
58 | n/a | def _have_socket_rds(): |
---|
59 | n/a | """Check whether RDS sockets are supported on this host.""" |
---|
60 | n/a | try: |
---|
61 | n/a | s = socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0) |
---|
62 | n/a | except (AttributeError, OSError): |
---|
63 | n/a | return False |
---|
64 | n/a | else: |
---|
65 | n/a | s.close() |
---|
66 | n/a | return True |
---|
67 | n/a | |
---|
68 | n/a | def _have_socket_alg(): |
---|
69 | n/a | """Check whether AF_ALG sockets are supported on this host.""" |
---|
70 | n/a | try: |
---|
71 | n/a | s = socket.socket(socket.AF_ALG, socket.SOCK_SEQPACKET, 0) |
---|
72 | n/a | except (AttributeError, OSError): |
---|
73 | n/a | return False |
---|
74 | n/a | else: |
---|
75 | n/a | s.close() |
---|
76 | n/a | return True |
---|
77 | n/a | |
---|
78 | n/a | HAVE_SOCKET_CAN = _have_socket_can() |
---|
79 | n/a | |
---|
80 | n/a | HAVE_SOCKET_RDS = _have_socket_rds() |
---|
81 | n/a | |
---|
82 | n/a | HAVE_SOCKET_ALG = _have_socket_alg() |
---|
83 | n/a | |
---|
84 | n/a | # Size in bytes of the int type |
---|
85 | n/a | SIZEOF_INT = array.array("i").itemsize |
---|
86 | n/a | |
---|
87 | n/a | class SocketTCPTest(unittest.TestCase): |
---|
88 | n/a | |
---|
89 | n/a | def setUp(self): |
---|
90 | n/a | self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
---|
91 | n/a | self.port = support.bind_port(self.serv) |
---|
92 | n/a | self.serv.listen() |
---|
93 | n/a | |
---|
94 | n/a | def tearDown(self): |
---|
95 | n/a | self.serv.close() |
---|
96 | n/a | self.serv = None |
---|
97 | n/a | |
---|
98 | n/a | class SocketUDPTest(unittest.TestCase): |
---|
99 | n/a | |
---|
100 | n/a | def setUp(self): |
---|
101 | n/a | self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
---|
102 | n/a | self.port = support.bind_port(self.serv) |
---|
103 | n/a | |
---|
104 | n/a | def tearDown(self): |
---|
105 | n/a | self.serv.close() |
---|
106 | n/a | self.serv = None |
---|
107 | n/a | |
---|
108 | n/a | class ThreadSafeCleanupTestCase(unittest.TestCase): |
---|
109 | n/a | """Subclass of unittest.TestCase with thread-safe cleanup methods. |
---|
110 | n/a | |
---|
111 | n/a | This subclass protects the addCleanup() and doCleanups() methods |
---|
112 | n/a | with a recursive lock. |
---|
113 | n/a | """ |
---|
114 | n/a | |
---|
115 | n/a | if threading: |
---|
116 | n/a | def __init__(self, *args, **kwargs): |
---|
117 | n/a | super().__init__(*args, **kwargs) |
---|
118 | n/a | self._cleanup_lock = threading.RLock() |
---|
119 | n/a | |
---|
120 | n/a | def addCleanup(self, *args, **kwargs): |
---|
121 | n/a | with self._cleanup_lock: |
---|
122 | n/a | return super().addCleanup(*args, **kwargs) |
---|
123 | n/a | |
---|
124 | n/a | def doCleanups(self, *args, **kwargs): |
---|
125 | n/a | with self._cleanup_lock: |
---|
126 | n/a | return super().doCleanups(*args, **kwargs) |
---|
127 | n/a | |
---|
128 | n/a | class SocketCANTest(unittest.TestCase): |
---|
129 | n/a | |
---|
130 | n/a | """To be able to run this test, a `vcan0` CAN interface can be created with |
---|
131 | n/a | the following commands: |
---|
132 | n/a | # modprobe vcan |
---|
133 | n/a | # ip link add dev vcan0 type vcan |
---|
134 | n/a | # ifconfig vcan0 up |
---|
135 | n/a | """ |
---|
136 | n/a | interface = 'vcan0' |
---|
137 | n/a | bufsize = 128 |
---|
138 | n/a | |
---|
139 | n/a | """The CAN frame structure is defined in <linux/can.h>: |
---|
140 | n/a | |
---|
141 | n/a | struct can_frame { |
---|
142 | n/a | canid_t can_id; /* 32 bit CAN_ID + EFF/RTR/ERR flags */ |
---|
143 | n/a | __u8 can_dlc; /* data length code: 0 .. 8 */ |
---|
144 | n/a | __u8 data[8] __attribute__((aligned(8))); |
---|
145 | n/a | }; |
---|
146 | n/a | """ |
---|
147 | n/a | can_frame_fmt = "=IB3x8s" |
---|
148 | n/a | can_frame_size = struct.calcsize(can_frame_fmt) |
---|
149 | n/a | |
---|
150 | n/a | """The Broadcast Management Command frame structure is defined |
---|
151 | n/a | in <linux/can/bcm.h>: |
---|
152 | n/a | |
---|
153 | n/a | struct bcm_msg_head { |
---|
154 | n/a | __u32 opcode; |
---|
155 | n/a | __u32 flags; |
---|
156 | n/a | __u32 count; |
---|
157 | n/a | struct timeval ival1, ival2; |
---|
158 | n/a | canid_t can_id; |
---|
159 | n/a | __u32 nframes; |
---|
160 | n/a | struct can_frame frames[0]; |
---|
161 | n/a | } |
---|
162 | n/a | |
---|
163 | n/a | `bcm_msg_head` must be 8 bytes aligned because of the `frames` member (see |
---|
164 | n/a | `struct can_frame` definition). Must use native not standard types for packing. |
---|
165 | n/a | """ |
---|
166 | n/a | bcm_cmd_msg_fmt = "@3I4l2I" |
---|
167 | n/a | bcm_cmd_msg_fmt += "x" * (struct.calcsize(bcm_cmd_msg_fmt) % 8) |
---|
168 | n/a | |
---|
169 | n/a | def setUp(self): |
---|
170 | n/a | self.s = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) |
---|
171 | n/a | self.addCleanup(self.s.close) |
---|
172 | n/a | try: |
---|
173 | n/a | self.s.bind((self.interface,)) |
---|
174 | n/a | except OSError: |
---|
175 | n/a | self.skipTest('network interface `%s` does not exist' % |
---|
176 | n/a | self.interface) |
---|
177 | n/a | |
---|
178 | n/a | |
---|
179 | n/a | class SocketRDSTest(unittest.TestCase): |
---|
180 | n/a | |
---|
181 | n/a | """To be able to run this test, the `rds` kernel module must be loaded: |
---|
182 | n/a | # modprobe rds |
---|
183 | n/a | """ |
---|
184 | n/a | bufsize = 8192 |
---|
185 | n/a | |
---|
186 | n/a | def setUp(self): |
---|
187 | n/a | self.serv = socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0) |
---|
188 | n/a | self.addCleanup(self.serv.close) |
---|
189 | n/a | try: |
---|
190 | n/a | self.port = support.bind_port(self.serv) |
---|
191 | n/a | except OSError: |
---|
192 | n/a | self.skipTest('unable to bind RDS socket') |
---|
193 | n/a | |
---|
194 | n/a | |
---|
195 | n/a | class ThreadableTest: |
---|
196 | n/a | """Threadable Test class |
---|
197 | n/a | |
---|
198 | n/a | The ThreadableTest class makes it easy to create a threaded |
---|
199 | n/a | client/server pair from an existing unit test. To create a |
---|
200 | n/a | new threaded class from an existing unit test, use multiple |
---|
201 | n/a | inheritance: |
---|
202 | n/a | |
---|
203 | n/a | class NewClass (OldClass, ThreadableTest): |
---|
204 | n/a | pass |
---|
205 | n/a | |
---|
206 | n/a | This class defines two new fixture functions with obvious |
---|
207 | n/a | purposes for overriding: |
---|
208 | n/a | |
---|
209 | n/a | clientSetUp () |
---|
210 | n/a | clientTearDown () |
---|
211 | n/a | |
---|
212 | n/a | Any new test functions within the class must then define |
---|
213 | n/a | tests in pairs, where the test name is preceded with a |
---|
214 | n/a | '_' to indicate the client portion of the test. Ex: |
---|
215 | n/a | |
---|
216 | n/a | def testFoo(self): |
---|
217 | n/a | # Server portion |
---|
218 | n/a | |
---|
219 | n/a | def _testFoo(self): |
---|
220 | n/a | # Client portion |
---|
221 | n/a | |
---|
222 | n/a | Any exceptions raised by the clients during their tests |
---|
223 | n/a | are caught and transferred to the main thread to alert |
---|
224 | n/a | the testing framework. |
---|
225 | n/a | |
---|
226 | n/a | Note, the server setup function cannot call any blocking |
---|
227 | n/a | functions that rely on the client thread during setup, |
---|
228 | n/a | unless serverExplicitReady() is called just before |
---|
229 | n/a | the blocking call (such as in setting up a client/server |
---|
230 | n/a | connection and performing the accept() in setUp(). |
---|
231 | n/a | """ |
---|
232 | n/a | |
---|
233 | n/a | def __init__(self): |
---|
234 | n/a | # Swap the true setup function |
---|
235 | n/a | self.__setUp = self.setUp |
---|
236 | n/a | self.__tearDown = self.tearDown |
---|
237 | n/a | self.setUp = self._setUp |
---|
238 | n/a | self.tearDown = self._tearDown |
---|
239 | n/a | |
---|
240 | n/a | def serverExplicitReady(self): |
---|
241 | n/a | """This method allows the server to explicitly indicate that |
---|
242 | n/a | it wants the client thread to proceed. This is useful if the |
---|
243 | n/a | server is about to execute a blocking routine that is |
---|
244 | n/a | dependent upon the client thread during its setup routine.""" |
---|
245 | n/a | self.server_ready.set() |
---|
246 | n/a | |
---|
247 | n/a | def _setUp(self): |
---|
248 | n/a | self.server_ready = threading.Event() |
---|
249 | n/a | self.client_ready = threading.Event() |
---|
250 | n/a | self.done = threading.Event() |
---|
251 | n/a | self.queue = queue.Queue(1) |
---|
252 | n/a | self.server_crashed = False |
---|
253 | n/a | |
---|
254 | n/a | # Do some munging to start the client test. |
---|
255 | n/a | methodname = self.id() |
---|
256 | n/a | i = methodname.rfind('.') |
---|
257 | n/a | methodname = methodname[i+1:] |
---|
258 | n/a | test_method = getattr(self, '_' + methodname) |
---|
259 | n/a | self.client_thread = thread.start_new_thread( |
---|
260 | n/a | self.clientRun, (test_method,)) |
---|
261 | n/a | |
---|
262 | n/a | try: |
---|
263 | n/a | self.__setUp() |
---|
264 | n/a | except: |
---|
265 | n/a | self.server_crashed = True |
---|
266 | n/a | raise |
---|
267 | n/a | finally: |
---|
268 | n/a | self.server_ready.set() |
---|
269 | n/a | self.client_ready.wait() |
---|
270 | n/a | |
---|
271 | n/a | def _tearDown(self): |
---|
272 | n/a | self.__tearDown() |
---|
273 | n/a | self.done.wait() |
---|
274 | n/a | |
---|
275 | n/a | if self.queue.qsize(): |
---|
276 | n/a | exc = self.queue.get() |
---|
277 | n/a | raise exc |
---|
278 | n/a | |
---|
279 | n/a | def clientRun(self, test_func): |
---|
280 | n/a | self.server_ready.wait() |
---|
281 | n/a | try: |
---|
282 | n/a | self.clientSetUp() |
---|
283 | n/a | except BaseException as e: |
---|
284 | n/a | self.queue.put(e) |
---|
285 | n/a | self.clientTearDown() |
---|
286 | n/a | return |
---|
287 | n/a | finally: |
---|
288 | n/a | self.client_ready.set() |
---|
289 | n/a | if self.server_crashed: |
---|
290 | n/a | self.clientTearDown() |
---|
291 | n/a | return |
---|
292 | n/a | if not hasattr(test_func, '__call__'): |
---|
293 | n/a | raise TypeError("test_func must be a callable function") |
---|
294 | n/a | try: |
---|
295 | n/a | test_func() |
---|
296 | n/a | except BaseException as e: |
---|
297 | n/a | self.queue.put(e) |
---|
298 | n/a | finally: |
---|
299 | n/a | self.clientTearDown() |
---|
300 | n/a | |
---|
301 | n/a | def clientSetUp(self): |
---|
302 | n/a | raise NotImplementedError("clientSetUp must be implemented.") |
---|
303 | n/a | |
---|
304 | n/a | def clientTearDown(self): |
---|
305 | n/a | self.done.set() |
---|
306 | n/a | thread.exit() |
---|
307 | n/a | |
---|
308 | n/a | class ThreadedTCPSocketTest(SocketTCPTest, ThreadableTest): |
---|
309 | n/a | |
---|
310 | n/a | def __init__(self, methodName='runTest'): |
---|
311 | n/a | SocketTCPTest.__init__(self, methodName=methodName) |
---|
312 | n/a | ThreadableTest.__init__(self) |
---|
313 | n/a | |
---|
314 | n/a | def clientSetUp(self): |
---|
315 | n/a | self.cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
---|
316 | n/a | |
---|
317 | n/a | def clientTearDown(self): |
---|
318 | n/a | self.cli.close() |
---|
319 | n/a | self.cli = None |
---|
320 | n/a | ThreadableTest.clientTearDown(self) |
---|
321 | n/a | |
---|
322 | n/a | class ThreadedUDPSocketTest(SocketUDPTest, ThreadableTest): |
---|
323 | n/a | |
---|
324 | n/a | def __init__(self, methodName='runTest'): |
---|
325 | n/a | SocketUDPTest.__init__(self, methodName=methodName) |
---|
326 | n/a | ThreadableTest.__init__(self) |
---|
327 | n/a | |
---|
328 | n/a | def clientSetUp(self): |
---|
329 | n/a | self.cli = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
---|
330 | n/a | |
---|
331 | n/a | def clientTearDown(self): |
---|
332 | n/a | self.cli.close() |
---|
333 | n/a | self.cli = None |
---|
334 | n/a | ThreadableTest.clientTearDown(self) |
---|
335 | n/a | |
---|
336 | n/a | class ThreadedCANSocketTest(SocketCANTest, ThreadableTest): |
---|
337 | n/a | |
---|
338 | n/a | def __init__(self, methodName='runTest'): |
---|
339 | n/a | SocketCANTest.__init__(self, methodName=methodName) |
---|
340 | n/a | ThreadableTest.__init__(self) |
---|
341 | n/a | |
---|
342 | n/a | def clientSetUp(self): |
---|
343 | n/a | self.cli = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) |
---|
344 | n/a | try: |
---|
345 | n/a | self.cli.bind((self.interface,)) |
---|
346 | n/a | except OSError: |
---|
347 | n/a | # skipTest should not be called here, and will be called in the |
---|
348 | n/a | # server instead |
---|
349 | n/a | pass |
---|
350 | n/a | |
---|
351 | n/a | def clientTearDown(self): |
---|
352 | n/a | self.cli.close() |
---|
353 | n/a | self.cli = None |
---|
354 | n/a | ThreadableTest.clientTearDown(self) |
---|
355 | n/a | |
---|
356 | n/a | class ThreadedRDSSocketTest(SocketRDSTest, ThreadableTest): |
---|
357 | n/a | |
---|
358 | n/a | def __init__(self, methodName='runTest'): |
---|
359 | n/a | SocketRDSTest.__init__(self, methodName=methodName) |
---|
360 | n/a | ThreadableTest.__init__(self) |
---|
361 | n/a | |
---|
362 | n/a | def clientSetUp(self): |
---|
363 | n/a | self.cli = socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0) |
---|
364 | n/a | try: |
---|
365 | n/a | # RDS sockets must be bound explicitly to send or receive data |
---|
366 | n/a | self.cli.bind((HOST, 0)) |
---|
367 | n/a | self.cli_addr = self.cli.getsockname() |
---|
368 | n/a | except OSError: |
---|
369 | n/a | # skipTest should not be called here, and will be called in the |
---|
370 | n/a | # server instead |
---|
371 | n/a | pass |
---|
372 | n/a | |
---|
373 | n/a | def clientTearDown(self): |
---|
374 | n/a | self.cli.close() |
---|
375 | n/a | self.cli = None |
---|
376 | n/a | ThreadableTest.clientTearDown(self) |
---|
377 | n/a | |
---|
378 | n/a | class SocketConnectedTest(ThreadedTCPSocketTest): |
---|
379 | n/a | """Socket tests for client-server connection. |
---|
380 | n/a | |
---|
381 | n/a | self.cli_conn is a client socket connected to the server. The |
---|
382 | n/a | setUp() method guarantees that it is connected to the server. |
---|
383 | n/a | """ |
---|
384 | n/a | |
---|
385 | n/a | def __init__(self, methodName='runTest'): |
---|
386 | n/a | ThreadedTCPSocketTest.__init__(self, methodName=methodName) |
---|
387 | n/a | |
---|
388 | n/a | def setUp(self): |
---|
389 | n/a | ThreadedTCPSocketTest.setUp(self) |
---|
390 | n/a | # Indicate explicitly we're ready for the client thread to |
---|
391 | n/a | # proceed and then perform the blocking call to accept |
---|
392 | n/a | self.serverExplicitReady() |
---|
393 | n/a | conn, addr = self.serv.accept() |
---|
394 | n/a | self.cli_conn = conn |
---|
395 | n/a | |
---|
396 | n/a | def tearDown(self): |
---|
397 | n/a | self.cli_conn.close() |
---|
398 | n/a | self.cli_conn = None |
---|
399 | n/a | ThreadedTCPSocketTest.tearDown(self) |
---|
400 | n/a | |
---|
401 | n/a | def clientSetUp(self): |
---|
402 | n/a | ThreadedTCPSocketTest.clientSetUp(self) |
---|
403 | n/a | self.cli.connect((HOST, self.port)) |
---|
404 | n/a | self.serv_conn = self.cli |
---|
405 | n/a | |
---|
406 | n/a | def clientTearDown(self): |
---|
407 | n/a | self.serv_conn.close() |
---|
408 | n/a | self.serv_conn = None |
---|
409 | n/a | ThreadedTCPSocketTest.clientTearDown(self) |
---|
410 | n/a | |
---|
411 | n/a | class SocketPairTest(unittest.TestCase, ThreadableTest): |
---|
412 | n/a | |
---|
413 | n/a | def __init__(self, methodName='runTest'): |
---|
414 | n/a | unittest.TestCase.__init__(self, methodName=methodName) |
---|
415 | n/a | ThreadableTest.__init__(self) |
---|
416 | n/a | |
---|
417 | n/a | def setUp(self): |
---|
418 | n/a | self.serv, self.cli = socket.socketpair() |
---|
419 | n/a | |
---|
420 | n/a | def tearDown(self): |
---|
421 | n/a | self.serv.close() |
---|
422 | n/a | self.serv = None |
---|
423 | n/a | |
---|
424 | n/a | def clientSetUp(self): |
---|
425 | n/a | pass |
---|
426 | n/a | |
---|
427 | n/a | def clientTearDown(self): |
---|
428 | n/a | self.cli.close() |
---|
429 | n/a | self.cli = None |
---|
430 | n/a | ThreadableTest.clientTearDown(self) |
---|
431 | n/a | |
---|
432 | n/a | |
---|
433 | n/a | # The following classes are used by the sendmsg()/recvmsg() tests. |
---|
434 | n/a | # Combining, for instance, ConnectedStreamTestMixin and TCPTestBase |
---|
435 | n/a | # gives a drop-in replacement for SocketConnectedTest, but different |
---|
436 | n/a | # address families can be used, and the attributes serv_addr and |
---|
437 | n/a | # cli_addr will be set to the addresses of the endpoints. |
---|
438 | n/a | |
---|
439 | n/a | class SocketTestBase(unittest.TestCase): |
---|
440 | n/a | """A base class for socket tests. |
---|
441 | n/a | |
---|
442 | n/a | Subclasses must provide methods newSocket() to return a new socket |
---|
443 | n/a | and bindSock(sock) to bind it to an unused address. |
---|
444 | n/a | |
---|
445 | n/a | Creates a socket self.serv and sets self.serv_addr to its address. |
---|
446 | n/a | """ |
---|
447 | n/a | |
---|
448 | n/a | def setUp(self): |
---|
449 | n/a | self.serv = self.newSocket() |
---|
450 | n/a | self.bindServer() |
---|
451 | n/a | |
---|
452 | n/a | def bindServer(self): |
---|
453 | n/a | """Bind server socket and set self.serv_addr to its address.""" |
---|
454 | n/a | self.bindSock(self.serv) |
---|
455 | n/a | self.serv_addr = self.serv.getsockname() |
---|
456 | n/a | |
---|
457 | n/a | def tearDown(self): |
---|
458 | n/a | self.serv.close() |
---|
459 | n/a | self.serv = None |
---|
460 | n/a | |
---|
461 | n/a | |
---|
462 | n/a | class SocketListeningTestMixin(SocketTestBase): |
---|
463 | n/a | """Mixin to listen on the server socket.""" |
---|
464 | n/a | |
---|
465 | n/a | def setUp(self): |
---|
466 | n/a | super().setUp() |
---|
467 | n/a | self.serv.listen() |
---|
468 | n/a | |
---|
469 | n/a | |
---|
470 | n/a | class ThreadedSocketTestMixin(ThreadSafeCleanupTestCase, SocketTestBase, |
---|
471 | n/a | ThreadableTest): |
---|
472 | n/a | """Mixin to add client socket and allow client/server tests. |
---|
473 | n/a | |
---|
474 | n/a | Client socket is self.cli and its address is self.cli_addr. See |
---|
475 | n/a | ThreadableTest for usage information. |
---|
476 | n/a | """ |
---|
477 | n/a | |
---|
478 | n/a | def __init__(self, *args, **kwargs): |
---|
479 | n/a | super().__init__(*args, **kwargs) |
---|
480 | n/a | ThreadableTest.__init__(self) |
---|
481 | n/a | |
---|
482 | n/a | def clientSetUp(self): |
---|
483 | n/a | self.cli = self.newClientSocket() |
---|
484 | n/a | self.bindClient() |
---|
485 | n/a | |
---|
486 | n/a | def newClientSocket(self): |
---|
487 | n/a | """Return a new socket for use as client.""" |
---|
488 | n/a | return self.newSocket() |
---|
489 | n/a | |
---|
490 | n/a | def bindClient(self): |
---|
491 | n/a | """Bind client socket and set self.cli_addr to its address.""" |
---|
492 | n/a | self.bindSock(self.cli) |
---|
493 | n/a | self.cli_addr = self.cli.getsockname() |
---|
494 | n/a | |
---|
495 | n/a | def clientTearDown(self): |
---|
496 | n/a | self.cli.close() |
---|
497 | n/a | self.cli = None |
---|
498 | n/a | ThreadableTest.clientTearDown(self) |
---|
499 | n/a | |
---|
500 | n/a | |
---|
501 | n/a | class ConnectedStreamTestMixin(SocketListeningTestMixin, |
---|
502 | n/a | ThreadedSocketTestMixin): |
---|
503 | n/a | """Mixin to allow client/server stream tests with connected client. |
---|
504 | n/a | |
---|
505 | n/a | Server's socket representing connection to client is self.cli_conn |
---|
506 | n/a | and client's connection to server is self.serv_conn. (Based on |
---|
507 | n/a | SocketConnectedTest.) |
---|
508 | n/a | """ |
---|
509 | n/a | |
---|
510 | n/a | def setUp(self): |
---|
511 | n/a | super().setUp() |
---|
512 | n/a | # Indicate explicitly we're ready for the client thread to |
---|
513 | n/a | # proceed and then perform the blocking call to accept |
---|
514 | n/a | self.serverExplicitReady() |
---|
515 | n/a | conn, addr = self.serv.accept() |
---|
516 | n/a | self.cli_conn = conn |
---|
517 | n/a | |
---|
518 | n/a | def tearDown(self): |
---|
519 | n/a | self.cli_conn.close() |
---|
520 | n/a | self.cli_conn = None |
---|
521 | n/a | super().tearDown() |
---|
522 | n/a | |
---|
523 | n/a | def clientSetUp(self): |
---|
524 | n/a | super().clientSetUp() |
---|
525 | n/a | self.cli.connect(self.serv_addr) |
---|
526 | n/a | self.serv_conn = self.cli |
---|
527 | n/a | |
---|
528 | n/a | def clientTearDown(self): |
---|
529 | n/a | try: |
---|
530 | n/a | self.serv_conn.close() |
---|
531 | n/a | self.serv_conn = None |
---|
532 | n/a | except AttributeError: |
---|
533 | n/a | pass |
---|
534 | n/a | super().clientTearDown() |
---|
535 | n/a | |
---|
536 | n/a | |
---|
537 | n/a | class UnixSocketTestBase(SocketTestBase): |
---|
538 | n/a | """Base class for Unix-domain socket tests.""" |
---|
539 | n/a | |
---|
540 | n/a | # This class is used for file descriptor passing tests, so we |
---|
541 | n/a | # create the sockets in a private directory so that other users |
---|
542 | n/a | # can't send anything that might be problematic for a privileged |
---|
543 | n/a | # user running the tests. |
---|
544 | n/a | |
---|
545 | n/a | def setUp(self): |
---|
546 | n/a | self.dir_path = tempfile.mkdtemp() |
---|
547 | n/a | self.addCleanup(os.rmdir, self.dir_path) |
---|
548 | n/a | super().setUp() |
---|
549 | n/a | |
---|
550 | n/a | def bindSock(self, sock): |
---|
551 | n/a | path = tempfile.mktemp(dir=self.dir_path) |
---|
552 | n/a | support.bind_unix_socket(sock, path) |
---|
553 | n/a | self.addCleanup(support.unlink, path) |
---|
554 | n/a | |
---|
555 | n/a | class UnixStreamBase(UnixSocketTestBase): |
---|
556 | n/a | """Base class for Unix-domain SOCK_STREAM tests.""" |
---|
557 | n/a | |
---|
558 | n/a | def newSocket(self): |
---|
559 | n/a | return socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
---|
560 | n/a | |
---|
561 | n/a | |
---|
562 | n/a | class InetTestBase(SocketTestBase): |
---|
563 | n/a | """Base class for IPv4 socket tests.""" |
---|
564 | n/a | |
---|
565 | n/a | host = HOST |
---|
566 | n/a | |
---|
567 | n/a | def setUp(self): |
---|
568 | n/a | super().setUp() |
---|
569 | n/a | self.port = self.serv_addr[1] |
---|
570 | n/a | |
---|
571 | n/a | def bindSock(self, sock): |
---|
572 | n/a | support.bind_port(sock, host=self.host) |
---|
573 | n/a | |
---|
574 | n/a | class TCPTestBase(InetTestBase): |
---|
575 | n/a | """Base class for TCP-over-IPv4 tests.""" |
---|
576 | n/a | |
---|
577 | n/a | def newSocket(self): |
---|
578 | n/a | return socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
---|
579 | n/a | |
---|
580 | n/a | class UDPTestBase(InetTestBase): |
---|
581 | n/a | """Base class for UDP-over-IPv4 tests.""" |
---|
582 | n/a | |
---|
583 | n/a | def newSocket(self): |
---|
584 | n/a | return socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
---|
585 | n/a | |
---|
586 | n/a | class SCTPStreamBase(InetTestBase): |
---|
587 | n/a | """Base class for SCTP tests in one-to-one (SOCK_STREAM) mode.""" |
---|
588 | n/a | |
---|
589 | n/a | def newSocket(self): |
---|
590 | n/a | return socket.socket(socket.AF_INET, socket.SOCK_STREAM, |
---|
591 | n/a | socket.IPPROTO_SCTP) |
---|
592 | n/a | |
---|
593 | n/a | |
---|
594 | n/a | class Inet6TestBase(InetTestBase): |
---|
595 | n/a | """Base class for IPv6 socket tests.""" |
---|
596 | n/a | |
---|
597 | n/a | host = support.HOSTv6 |
---|
598 | n/a | |
---|
599 | n/a | class UDP6TestBase(Inet6TestBase): |
---|
600 | n/a | """Base class for UDP-over-IPv6 tests.""" |
---|
601 | n/a | |
---|
602 | n/a | def newSocket(self): |
---|
603 | n/a | return socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) |
---|
604 | n/a | |
---|
605 | n/a | |
---|
606 | n/a | # Test-skipping decorators for use with ThreadableTest. |
---|
607 | n/a | |
---|
608 | n/a | def skipWithClientIf(condition, reason): |
---|
609 | n/a | """Skip decorated test if condition is true, add client_skip decorator. |
---|
610 | n/a | |
---|
611 | n/a | If the decorated object is not a class, sets its attribute |
---|
612 | n/a | "client_skip" to a decorator which will return an empty function |
---|
613 | n/a | if the test is to be skipped, or the original function if it is |
---|
614 | n/a | not. This can be used to avoid running the client part of a |
---|
615 | n/a | skipped test when using ThreadableTest. |
---|
616 | n/a | """ |
---|
617 | n/a | def client_pass(*args, **kwargs): |
---|
618 | n/a | pass |
---|
619 | n/a | def skipdec(obj): |
---|
620 | n/a | retval = unittest.skip(reason)(obj) |
---|
621 | n/a | if not isinstance(obj, type): |
---|
622 | n/a | retval.client_skip = lambda f: client_pass |
---|
623 | n/a | return retval |
---|
624 | n/a | def noskipdec(obj): |
---|
625 | n/a | if not (isinstance(obj, type) or hasattr(obj, "client_skip")): |
---|
626 | n/a | obj.client_skip = lambda f: f |
---|
627 | n/a | return obj |
---|
628 | n/a | return skipdec if condition else noskipdec |
---|
629 | n/a | |
---|
630 | n/a | |
---|
631 | n/a | def requireAttrs(obj, *attributes): |
---|
632 | n/a | """Skip decorated test if obj is missing any of the given attributes. |
---|
633 | n/a | |
---|
634 | n/a | Sets client_skip attribute as skipWithClientIf() does. |
---|
635 | n/a | """ |
---|
636 | n/a | missing = [name for name in attributes if not hasattr(obj, name)] |
---|
637 | n/a | return skipWithClientIf( |
---|
638 | n/a | missing, "don't have " + ", ".join(name for name in missing)) |
---|
639 | n/a | |
---|
640 | n/a | |
---|
641 | n/a | def requireSocket(*args): |
---|
642 | n/a | """Skip decorated test if a socket cannot be created with given arguments. |
---|
643 | n/a | |
---|
644 | n/a | When an argument is given as a string, will use the value of that |
---|
645 | n/a | attribute of the socket module, or skip the test if it doesn't |
---|
646 | n/a | exist. Sets client_skip attribute as skipWithClientIf() does. |
---|
647 | n/a | """ |
---|
648 | n/a | err = None |
---|
649 | n/a | missing = [obj for obj in args if |
---|
650 | n/a | isinstance(obj, str) and not hasattr(socket, obj)] |
---|
651 | n/a | if missing: |
---|
652 | n/a | err = "don't have " + ", ".join(name for name in missing) |
---|
653 | n/a | else: |
---|
654 | n/a | callargs = [getattr(socket, obj) if isinstance(obj, str) else obj |
---|
655 | n/a | for obj in args] |
---|
656 | n/a | try: |
---|
657 | n/a | s = socket.socket(*callargs) |
---|
658 | n/a | except OSError as e: |
---|
659 | n/a | # XXX: check errno? |
---|
660 | n/a | err = str(e) |
---|
661 | n/a | else: |
---|
662 | n/a | s.close() |
---|
663 | n/a | return skipWithClientIf( |
---|
664 | n/a | err is not None, |
---|
665 | n/a | "can't create socket({0}): {1}".format( |
---|
666 | n/a | ", ".join(str(o) for o in args), err)) |
---|
667 | n/a | |
---|
668 | n/a | |
---|
669 | n/a | ####################################################################### |
---|
670 | n/a | ## Begin Tests |
---|
671 | n/a | |
---|
672 | n/a | class GeneralModuleTests(unittest.TestCase): |
---|
673 | n/a | |
---|
674 | n/a | def test_SocketType_is_socketobject(self): |
---|
675 | n/a | import _socket |
---|
676 | n/a | self.assertTrue(socket.SocketType is _socket.socket) |
---|
677 | n/a | s = socket.socket() |
---|
678 | n/a | self.assertIsInstance(s, socket.SocketType) |
---|
679 | n/a | s.close() |
---|
680 | n/a | |
---|
681 | n/a | def test_repr(self): |
---|
682 | n/a | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
---|
683 | n/a | with s: |
---|
684 | n/a | self.assertIn('fd=%i' % s.fileno(), repr(s)) |
---|
685 | n/a | self.assertIn('family=%s' % socket.AF_INET, repr(s)) |
---|
686 | n/a | self.assertIn('type=%s' % socket.SOCK_STREAM, repr(s)) |
---|
687 | n/a | self.assertIn('proto=0', repr(s)) |
---|
688 | n/a | self.assertNotIn('raddr', repr(s)) |
---|
689 | n/a | s.bind(('127.0.0.1', 0)) |
---|
690 | n/a | self.assertIn('laddr', repr(s)) |
---|
691 | n/a | self.assertIn(str(s.getsockname()), repr(s)) |
---|
692 | n/a | self.assertIn('[closed]', repr(s)) |
---|
693 | n/a | self.assertNotIn('laddr', repr(s)) |
---|
694 | n/a | |
---|
695 | n/a | @unittest.skipUnless(_socket is not None, 'need _socket module') |
---|
696 | n/a | def test_csocket_repr(self): |
---|
697 | n/a | s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM) |
---|
698 | n/a | try: |
---|
699 | n/a | expected = ('<socket object, fd=%s, family=%s, type=%s, proto=%s>' |
---|
700 | n/a | % (s.fileno(), s.family, s.type, s.proto)) |
---|
701 | n/a | self.assertEqual(repr(s), expected) |
---|
702 | n/a | finally: |
---|
703 | n/a | s.close() |
---|
704 | n/a | expected = ('<socket object, fd=-1, family=%s, type=%s, proto=%s>' |
---|
705 | n/a | % (s.family, s.type, s.proto)) |
---|
706 | n/a | self.assertEqual(repr(s), expected) |
---|
707 | n/a | |
---|
708 | n/a | def test_weakref(self): |
---|
709 | n/a | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
---|
710 | n/a | p = proxy(s) |
---|
711 | n/a | self.assertEqual(p.fileno(), s.fileno()) |
---|
712 | n/a | s.close() |
---|
713 | n/a | s = None |
---|
714 | n/a | try: |
---|
715 | n/a | p.fileno() |
---|
716 | n/a | except ReferenceError: |
---|
717 | n/a | pass |
---|
718 | n/a | else: |
---|
719 | n/a | self.fail('Socket proxy still exists') |
---|
720 | n/a | |
---|
721 | n/a | def testSocketError(self): |
---|
722 | n/a | # Testing socket module exceptions |
---|
723 | n/a | msg = "Error raising socket exception (%s)." |
---|
724 | n/a | with self.assertRaises(OSError, msg=msg % 'OSError'): |
---|
725 | n/a | raise OSError |
---|
726 | n/a | with self.assertRaises(OSError, msg=msg % 'socket.herror'): |
---|
727 | n/a | raise socket.herror |
---|
728 | n/a | with self.assertRaises(OSError, msg=msg % 'socket.gaierror'): |
---|
729 | n/a | raise socket.gaierror |
---|
730 | n/a | |
---|
731 | n/a | def testSendtoErrors(self): |
---|
732 | n/a | # Testing that sendto doesn't mask failures. See #10169. |
---|
733 | n/a | s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
---|
734 | n/a | self.addCleanup(s.close) |
---|
735 | n/a | s.bind(('', 0)) |
---|
736 | n/a | sockname = s.getsockname() |
---|
737 | n/a | # 2 args |
---|
738 | n/a | with self.assertRaises(TypeError) as cm: |
---|
739 | n/a | s.sendto('\u2620', sockname) |
---|
740 | n/a | self.assertEqual(str(cm.exception), |
---|
741 | n/a | "a bytes-like object is required, not 'str'") |
---|
742 | n/a | with self.assertRaises(TypeError) as cm: |
---|
743 | n/a | s.sendto(5j, sockname) |
---|
744 | n/a | self.assertEqual(str(cm.exception), |
---|
745 | n/a | "a bytes-like object is required, not 'complex'") |
---|
746 | n/a | with self.assertRaises(TypeError) as cm: |
---|
747 | n/a | s.sendto(b'foo', None) |
---|
748 | n/a | self.assertIn('not NoneType',str(cm.exception)) |
---|
749 | n/a | # 3 args |
---|
750 | n/a | with self.assertRaises(TypeError) as cm: |
---|
751 | n/a | s.sendto('\u2620', 0, sockname) |
---|
752 | n/a | self.assertEqual(str(cm.exception), |
---|
753 | n/a | "a bytes-like object is required, not 'str'") |
---|
754 | n/a | with self.assertRaises(TypeError) as cm: |
---|
755 | n/a | s.sendto(5j, 0, sockname) |
---|
756 | n/a | self.assertEqual(str(cm.exception), |
---|
757 | n/a | "a bytes-like object is required, not 'complex'") |
---|
758 | n/a | with self.assertRaises(TypeError) as cm: |
---|
759 | n/a | s.sendto(b'foo', 0, None) |
---|
760 | n/a | self.assertIn('not NoneType', str(cm.exception)) |
---|
761 | n/a | with self.assertRaises(TypeError) as cm: |
---|
762 | n/a | s.sendto(b'foo', 'bar', sockname) |
---|
763 | n/a | self.assertIn('an integer is required', str(cm.exception)) |
---|
764 | n/a | with self.assertRaises(TypeError) as cm: |
---|
765 | n/a | s.sendto(b'foo', None, None) |
---|
766 | n/a | self.assertIn('an integer is required', str(cm.exception)) |
---|
767 | n/a | # wrong number of args |
---|
768 | n/a | with self.assertRaises(TypeError) as cm: |
---|
769 | n/a | s.sendto(b'foo') |
---|
770 | n/a | self.assertIn('(1 given)', str(cm.exception)) |
---|
771 | n/a | with self.assertRaises(TypeError) as cm: |
---|
772 | n/a | s.sendto(b'foo', 0, sockname, 4) |
---|
773 | n/a | self.assertIn('(4 given)', str(cm.exception)) |
---|
774 | n/a | |
---|
775 | n/a | def testCrucialConstants(self): |
---|
776 | n/a | # Testing for mission critical constants |
---|
777 | n/a | socket.AF_INET |
---|
778 | n/a | socket.SOCK_STREAM |
---|
779 | n/a | socket.SOCK_DGRAM |
---|
780 | n/a | socket.SOCK_RAW |
---|
781 | n/a | socket.SOCK_RDM |
---|
782 | n/a | socket.SOCK_SEQPACKET |
---|
783 | n/a | socket.SOL_SOCKET |
---|
784 | n/a | socket.SO_REUSEADDR |
---|
785 | n/a | |
---|
786 | n/a | def testHostnameRes(self): |
---|
787 | n/a | # Testing hostname resolution mechanisms |
---|
788 | n/a | hostname = socket.gethostname() |
---|
789 | n/a | try: |
---|
790 | n/a | ip = socket.gethostbyname(hostname) |
---|
791 | n/a | except OSError: |
---|
792 | n/a | # Probably name lookup wasn't set up right; skip this test |
---|
793 | n/a | self.skipTest('name lookup failure') |
---|
794 | n/a | self.assertTrue(ip.find('.') >= 0, "Error resolving host to ip.") |
---|
795 | n/a | try: |
---|
796 | n/a | hname, aliases, ipaddrs = socket.gethostbyaddr(ip) |
---|
797 | n/a | except OSError: |
---|
798 | n/a | # Probably a similar problem as above; skip this test |
---|
799 | n/a | self.skipTest('name lookup failure') |
---|
800 | n/a | all_host_names = [hostname, hname] + aliases |
---|
801 | n/a | fqhn = socket.getfqdn(ip) |
---|
802 | n/a | if not fqhn in all_host_names: |
---|
803 | n/a | self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names))) |
---|
804 | n/a | |
---|
805 | n/a | def test_host_resolution(self): |
---|
806 | n/a | for addr in ['0.1.1.~1', '1+.1.1.1', '::1q', '::1::2', |
---|
807 | n/a | '1:1:1:1:1:1:1:1:1']: |
---|
808 | n/a | self.assertRaises(OSError, socket.gethostbyname, addr) |
---|
809 | n/a | self.assertRaises(OSError, socket.gethostbyaddr, addr) |
---|
810 | n/a | |
---|
811 | n/a | for addr in [support.HOST, '10.0.0.1', '255.255.255.255']: |
---|
812 | n/a | self.assertEqual(socket.gethostbyname(addr), addr) |
---|
813 | n/a | |
---|
814 | n/a | # we don't test support.HOSTv6 because there's a chance it doesn't have |
---|
815 | n/a | # a matching name entry (e.g. 'ip6-localhost') |
---|
816 | n/a | for host in [support.HOST]: |
---|
817 | n/a | self.assertIn(host, socket.gethostbyaddr(host)[2]) |
---|
818 | n/a | |
---|
819 | n/a | @unittest.skipUnless(hasattr(socket, 'sethostname'), "test needs socket.sethostname()") |
---|
820 | n/a | @unittest.skipUnless(hasattr(socket, 'gethostname'), "test needs socket.gethostname()") |
---|
821 | n/a | def test_sethostname(self): |
---|
822 | n/a | oldhn = socket.gethostname() |
---|
823 | n/a | try: |
---|
824 | n/a | socket.sethostname('new') |
---|
825 | n/a | except OSError as e: |
---|
826 | n/a | if e.errno == errno.EPERM: |
---|
827 | n/a | self.skipTest("test should be run as root") |
---|
828 | n/a | else: |
---|
829 | n/a | raise |
---|
830 | n/a | try: |
---|
831 | n/a | # running test as root! |
---|
832 | n/a | self.assertEqual(socket.gethostname(), 'new') |
---|
833 | n/a | # Should work with bytes objects too |
---|
834 | n/a | socket.sethostname(b'bar') |
---|
835 | n/a | self.assertEqual(socket.gethostname(), 'bar') |
---|
836 | n/a | finally: |
---|
837 | n/a | socket.sethostname(oldhn) |
---|
838 | n/a | |
---|
839 | n/a | @unittest.skipUnless(hasattr(socket, 'if_nameindex'), |
---|
840 | n/a | 'socket.if_nameindex() not available.') |
---|
841 | n/a | def testInterfaceNameIndex(self): |
---|
842 | n/a | interfaces = socket.if_nameindex() |
---|
843 | n/a | for index, name in interfaces: |
---|
844 | n/a | self.assertIsInstance(index, int) |
---|
845 | n/a | self.assertIsInstance(name, str) |
---|
846 | n/a | # interface indices are non-zero integers |
---|
847 | n/a | self.assertGreater(index, 0) |
---|
848 | n/a | _index = socket.if_nametoindex(name) |
---|
849 | n/a | self.assertIsInstance(_index, int) |
---|
850 | n/a | self.assertEqual(index, _index) |
---|
851 | n/a | _name = socket.if_indextoname(index) |
---|
852 | n/a | self.assertIsInstance(_name, str) |
---|
853 | n/a | self.assertEqual(name, _name) |
---|
854 | n/a | |
---|
855 | n/a | @unittest.skipUnless(hasattr(socket, 'if_nameindex'), |
---|
856 | n/a | 'socket.if_nameindex() not available.') |
---|
857 | n/a | def testInvalidInterfaceNameIndex(self): |
---|
858 | n/a | # test nonexistent interface index/name |
---|
859 | n/a | self.assertRaises(OSError, socket.if_indextoname, 0) |
---|
860 | n/a | self.assertRaises(OSError, socket.if_nametoindex, '_DEADBEEF') |
---|
861 | n/a | # test with invalid values |
---|
862 | n/a | self.assertRaises(TypeError, socket.if_nametoindex, 0) |
---|
863 | n/a | self.assertRaises(TypeError, socket.if_indextoname, '_DEADBEEF') |
---|
864 | n/a | |
---|
865 | n/a | @unittest.skipUnless(hasattr(sys, 'getrefcount'), |
---|
866 | n/a | 'test needs sys.getrefcount()') |
---|
867 | n/a | def testRefCountGetNameInfo(self): |
---|
868 | n/a | # Testing reference count for getnameinfo |
---|
869 | n/a | try: |
---|
870 | n/a | # On some versions, this loses a reference |
---|
871 | n/a | orig = sys.getrefcount(__name__) |
---|
872 | n/a | socket.getnameinfo(__name__,0) |
---|
873 | n/a | except TypeError: |
---|
874 | n/a | if sys.getrefcount(__name__) != orig: |
---|
875 | n/a | self.fail("socket.getnameinfo loses a reference") |
---|
876 | n/a | |
---|
877 | n/a | def testInterpreterCrash(self): |
---|
878 | n/a | # Making sure getnameinfo doesn't crash the interpreter |
---|
879 | n/a | try: |
---|
880 | n/a | # On some versions, this crashes the interpreter. |
---|
881 | n/a | socket.getnameinfo(('x', 0, 0, 0), 0) |
---|
882 | n/a | except OSError: |
---|
883 | n/a | pass |
---|
884 | n/a | |
---|
885 | n/a | def testNtoH(self): |
---|
886 | n/a | # This just checks that htons etc. are their own inverse, |
---|
887 | n/a | # when looking at the lower 16 or 32 bits. |
---|
888 | n/a | sizes = {socket.htonl: 32, socket.ntohl: 32, |
---|
889 | n/a | socket.htons: 16, socket.ntohs: 16} |
---|
890 | n/a | for func, size in sizes.items(): |
---|
891 | n/a | mask = (1<<size) - 1 |
---|
892 | n/a | for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210): |
---|
893 | n/a | self.assertEqual(i & mask, func(func(i&mask)) & mask) |
---|
894 | n/a | |
---|
895 | n/a | swapped = func(mask) |
---|
896 | n/a | self.assertEqual(swapped & mask, mask) |
---|
897 | n/a | self.assertRaises(OverflowError, func, 1<<34) |
---|
898 | n/a | |
---|
899 | n/a | def testNtoHErrors(self): |
---|
900 | n/a | import _testcapi |
---|
901 | n/a | s_good_values = [0, 1, 2, 0xffff] |
---|
902 | n/a | l_good_values = s_good_values + [0xffffffff] |
---|
903 | n/a | l_bad_values = [-1, -2, 1<<32, 1<<1000] |
---|
904 | n/a | s_bad_values = l_bad_values + [_testcapi.INT_MIN - 1, |
---|
905 | n/a | _testcapi.INT_MAX + 1] |
---|
906 | n/a | s_deprecated_values = [1<<16, _testcapi.INT_MAX] |
---|
907 | n/a | for k in s_good_values: |
---|
908 | n/a | socket.ntohs(k) |
---|
909 | n/a | socket.htons(k) |
---|
910 | n/a | for k in l_good_values: |
---|
911 | n/a | socket.ntohl(k) |
---|
912 | n/a | socket.htonl(k) |
---|
913 | n/a | for k in s_bad_values: |
---|
914 | n/a | self.assertRaises(OverflowError, socket.ntohs, k) |
---|
915 | n/a | self.assertRaises(OverflowError, socket.htons, k) |
---|
916 | n/a | for k in l_bad_values: |
---|
917 | n/a | self.assertRaises(OverflowError, socket.ntohl, k) |
---|
918 | n/a | self.assertRaises(OverflowError, socket.htonl, k) |
---|
919 | n/a | for k in s_deprecated_values: |
---|
920 | n/a | self.assertWarns(DeprecationWarning, socket.ntohs, k) |
---|
921 | n/a | self.assertWarns(DeprecationWarning, socket.htons, k) |
---|
922 | n/a | |
---|
923 | n/a | def testGetServBy(self): |
---|
924 | n/a | eq = self.assertEqual |
---|
925 | n/a | # Find one service that exists, then check all the related interfaces. |
---|
926 | n/a | # I've ordered this by protocols that have both a tcp and udp |
---|
927 | n/a | # protocol, at least for modern Linuxes. |
---|
928 | n/a | if (sys.platform.startswith(('freebsd', 'netbsd', 'gnukfreebsd')) |
---|
929 | n/a | or sys.platform in ('linux', 'darwin')): |
---|
930 | n/a | # avoid the 'echo' service on this platform, as there is an |
---|
931 | n/a | # assumption breaking non-standard port/protocol entry |
---|
932 | n/a | services = ('daytime', 'qotd', 'domain') |
---|
933 | n/a | else: |
---|
934 | n/a | services = ('echo', 'daytime', 'domain') |
---|
935 | n/a | for service in services: |
---|
936 | n/a | try: |
---|
937 | n/a | port = socket.getservbyname(service, 'tcp') |
---|
938 | n/a | break |
---|
939 | n/a | except OSError: |
---|
940 | n/a | pass |
---|
941 | n/a | else: |
---|
942 | n/a | raise OSError |
---|
943 | n/a | # Try same call with optional protocol omitted |
---|
944 | n/a | # Issue #26936: Android getservbyname() was broken before API 23. |
---|
945 | n/a | if (not hasattr(sys, 'getandroidapilevel') or |
---|
946 | n/a | sys.getandroidapilevel() >= 23): |
---|
947 | n/a | port2 = socket.getservbyname(service) |
---|
948 | n/a | eq(port, port2) |
---|
949 | n/a | # Try udp, but don't barf if it doesn't exist |
---|
950 | n/a | try: |
---|
951 | n/a | udpport = socket.getservbyname(service, 'udp') |
---|
952 | n/a | except OSError: |
---|
953 | n/a | udpport = None |
---|
954 | n/a | else: |
---|
955 | n/a | eq(udpport, port) |
---|
956 | n/a | # Now make sure the lookup by port returns the same service name |
---|
957 | n/a | # Issue #26936: Android getservbyport() is broken. |
---|
958 | n/a | if not support.is_android: |
---|
959 | n/a | eq(socket.getservbyport(port2), service) |
---|
960 | n/a | eq(socket.getservbyport(port, 'tcp'), service) |
---|
961 | n/a | if udpport is not None: |
---|
962 | n/a | eq(socket.getservbyport(udpport, 'udp'), service) |
---|
963 | n/a | # Make sure getservbyport does not accept out of range ports. |
---|
964 | n/a | self.assertRaises(OverflowError, socket.getservbyport, -1) |
---|
965 | n/a | self.assertRaises(OverflowError, socket.getservbyport, 65536) |
---|
966 | n/a | |
---|
967 | n/a | def testDefaultTimeout(self): |
---|
968 | n/a | # Testing default timeout |
---|
969 | n/a | # The default timeout should initially be None |
---|
970 | n/a | self.assertEqual(socket.getdefaulttimeout(), None) |
---|
971 | n/a | s = socket.socket() |
---|
972 | n/a | self.assertEqual(s.gettimeout(), None) |
---|
973 | n/a | s.close() |
---|
974 | n/a | |
---|
975 | n/a | # Set the default timeout to 10, and see if it propagates |
---|
976 | n/a | socket.setdefaulttimeout(10) |
---|
977 | n/a | self.assertEqual(socket.getdefaulttimeout(), 10) |
---|
978 | n/a | s = socket.socket() |
---|
979 | n/a | self.assertEqual(s.gettimeout(), 10) |
---|
980 | n/a | s.close() |
---|
981 | n/a | |
---|
982 | n/a | # Reset the default timeout to None, and see if it propagates |
---|
983 | n/a | socket.setdefaulttimeout(None) |
---|
984 | n/a | self.assertEqual(socket.getdefaulttimeout(), None) |
---|
985 | n/a | s = socket.socket() |
---|
986 | n/a | self.assertEqual(s.gettimeout(), None) |
---|
987 | n/a | s.close() |
---|
988 | n/a | |
---|
989 | n/a | # Check that setting it to an invalid value raises ValueError |
---|
990 | n/a | self.assertRaises(ValueError, socket.setdefaulttimeout, -1) |
---|
991 | n/a | |
---|
992 | n/a | # Check that setting it to an invalid type raises TypeError |
---|
993 | n/a | self.assertRaises(TypeError, socket.setdefaulttimeout, "spam") |
---|
994 | n/a | |
---|
995 | n/a | @unittest.skipUnless(hasattr(socket, 'inet_aton'), |
---|
996 | n/a | 'test needs socket.inet_aton()') |
---|
997 | n/a | def testIPv4_inet_aton_fourbytes(self): |
---|
998 | n/a | # Test that issue1008086 and issue767150 are fixed. |
---|
999 | n/a | # It must return 4 bytes. |
---|
1000 | n/a | self.assertEqual(b'\x00'*4, socket.inet_aton('0.0.0.0')) |
---|
1001 | n/a | self.assertEqual(b'\xff'*4, socket.inet_aton('255.255.255.255')) |
---|
1002 | n/a | |
---|
1003 | n/a | @unittest.skipUnless(hasattr(socket, 'inet_pton'), |
---|
1004 | n/a | 'test needs socket.inet_pton()') |
---|
1005 | n/a | def testIPv4toString(self): |
---|
1006 | n/a | from socket import inet_aton as f, inet_pton, AF_INET |
---|
1007 | n/a | g = lambda a: inet_pton(AF_INET, a) |
---|
1008 | n/a | |
---|
1009 | n/a | assertInvalid = lambda func,a: self.assertRaises( |
---|
1010 | n/a | (OSError, ValueError), func, a |
---|
1011 | n/a | ) |
---|
1012 | n/a | |
---|
1013 | n/a | self.assertEqual(b'\x00\x00\x00\x00', f('0.0.0.0')) |
---|
1014 | n/a | self.assertEqual(b'\xff\x00\xff\x00', f('255.0.255.0')) |
---|
1015 | n/a | self.assertEqual(b'\xaa\xaa\xaa\xaa', f('170.170.170.170')) |
---|
1016 | n/a | self.assertEqual(b'\x01\x02\x03\x04', f('1.2.3.4')) |
---|
1017 | n/a | self.assertEqual(b'\xff\xff\xff\xff', f('255.255.255.255')) |
---|
1018 | n/a | assertInvalid(f, '0.0.0.') |
---|
1019 | n/a | assertInvalid(f, '300.0.0.0') |
---|
1020 | n/a | assertInvalid(f, 'a.0.0.0') |
---|
1021 | n/a | assertInvalid(f, '1.2.3.4.5') |
---|
1022 | n/a | assertInvalid(f, '::1') |
---|
1023 | n/a | |
---|
1024 | n/a | self.assertEqual(b'\x00\x00\x00\x00', g('0.0.0.0')) |
---|
1025 | n/a | self.assertEqual(b'\xff\x00\xff\x00', g('255.0.255.0')) |
---|
1026 | n/a | self.assertEqual(b'\xaa\xaa\xaa\xaa', g('170.170.170.170')) |
---|
1027 | n/a | self.assertEqual(b'\xff\xff\xff\xff', g('255.255.255.255')) |
---|
1028 | n/a | assertInvalid(g, '0.0.0.') |
---|
1029 | n/a | assertInvalid(g, '300.0.0.0') |
---|
1030 | n/a | assertInvalid(g, 'a.0.0.0') |
---|
1031 | n/a | assertInvalid(g, '1.2.3.4.5') |
---|
1032 | n/a | assertInvalid(g, '::1') |
---|
1033 | n/a | |
---|
1034 | n/a | @unittest.skipUnless(hasattr(socket, 'inet_pton'), |
---|
1035 | n/a | 'test needs socket.inet_pton()') |
---|
1036 | n/a | def testIPv6toString(self): |
---|
1037 | n/a | try: |
---|
1038 | n/a | from socket import inet_pton, AF_INET6, has_ipv6 |
---|
1039 | n/a | if not has_ipv6: |
---|
1040 | n/a | self.skipTest('IPv6 not available') |
---|
1041 | n/a | except ImportError: |
---|
1042 | n/a | self.skipTest('could not import needed symbols from socket') |
---|
1043 | n/a | |
---|
1044 | n/a | if sys.platform == "win32": |
---|
1045 | n/a | try: |
---|
1046 | n/a | inet_pton(AF_INET6, '::') |
---|
1047 | n/a | except OSError as e: |
---|
1048 | n/a | if e.winerror == 10022: |
---|
1049 | n/a | self.skipTest('IPv6 might not be supported') |
---|
1050 | n/a | |
---|
1051 | n/a | f = lambda a: inet_pton(AF_INET6, a) |
---|
1052 | n/a | assertInvalid = lambda a: self.assertRaises( |
---|
1053 | n/a | (OSError, ValueError), f, a |
---|
1054 | n/a | ) |
---|
1055 | n/a | |
---|
1056 | n/a | self.assertEqual(b'\x00' * 16, f('::')) |
---|
1057 | n/a | self.assertEqual(b'\x00' * 16, f('0::0')) |
---|
1058 | n/a | self.assertEqual(b'\x00\x01' + b'\x00' * 14, f('1::')) |
---|
1059 | n/a | self.assertEqual( |
---|
1060 | n/a | b'\x45\xef\x76\xcb\x00\x1a\x56\xef\xaf\xeb\x0b\xac\x19\x24\xae\xae', |
---|
1061 | n/a | f('45ef:76cb:1a:56ef:afeb:bac:1924:aeae') |
---|
1062 | n/a | ) |
---|
1063 | n/a | self.assertEqual( |
---|
1064 | n/a | b'\xad\x42\x0a\xbc' + b'\x00' * 4 + b'\x01\x27\x00\x00\x02\x54\x00\x02', |
---|
1065 | n/a | f('ad42:abc::127:0:254:2') |
---|
1066 | n/a | ) |
---|
1067 | n/a | self.assertEqual(b'\x00\x12\x00\x0a' + b'\x00' * 12, f('12:a::')) |
---|
1068 | n/a | assertInvalid('0x20::') |
---|
1069 | n/a | assertInvalid(':::') |
---|
1070 | n/a | assertInvalid('::0::') |
---|
1071 | n/a | assertInvalid('1::abc::') |
---|
1072 | n/a | assertInvalid('1::abc::def') |
---|
1073 | n/a | assertInvalid('1:2:3:4:5:6:') |
---|
1074 | n/a | assertInvalid('1:2:3:4:5:6') |
---|
1075 | n/a | assertInvalid('1:2:3:4:5:6:7:8:') |
---|
1076 | n/a | assertInvalid('1:2:3:4:5:6:7:8:0') |
---|
1077 | n/a | |
---|
1078 | n/a | self.assertEqual(b'\x00' * 12 + b'\xfe\x2a\x17\x40', |
---|
1079 | n/a | f('::254.42.23.64') |
---|
1080 | n/a | ) |
---|
1081 | n/a | self.assertEqual( |
---|
1082 | n/a | b'\x00\x42' + b'\x00' * 8 + b'\xa2\x9b\xfe\x2a\x17\x40', |
---|
1083 | n/a | f('42::a29b:254.42.23.64') |
---|
1084 | n/a | ) |
---|
1085 | n/a | self.assertEqual( |
---|
1086 | n/a | b'\x00\x42\xa8\xb9\x00\x00\x00\x02\xff\xff\xa2\x9b\xfe\x2a\x17\x40', |
---|
1087 | n/a | f('42:a8b9:0:2:ffff:a29b:254.42.23.64') |
---|
1088 | n/a | ) |
---|
1089 | n/a | assertInvalid('255.254.253.252') |
---|
1090 | n/a | assertInvalid('1::260.2.3.0') |
---|
1091 | n/a | assertInvalid('1::0.be.e.0') |
---|
1092 | n/a | assertInvalid('1:2:3:4:5:6:7:1.2.3.4') |
---|
1093 | n/a | assertInvalid('::1.2.3.4:0') |
---|
1094 | n/a | assertInvalid('0.100.200.0:3:4:5:6:7:8') |
---|
1095 | n/a | |
---|
1096 | n/a | @unittest.skipUnless(hasattr(socket, 'inet_ntop'), |
---|
1097 | n/a | 'test needs socket.inet_ntop()') |
---|
1098 | n/a | def testStringToIPv4(self): |
---|
1099 | n/a | from socket import inet_ntoa as f, inet_ntop, AF_INET |
---|
1100 | n/a | g = lambda a: inet_ntop(AF_INET, a) |
---|
1101 | n/a | assertInvalid = lambda func,a: self.assertRaises( |
---|
1102 | n/a | (OSError, ValueError), func, a |
---|
1103 | n/a | ) |
---|
1104 | n/a | |
---|
1105 | n/a | self.assertEqual('1.0.1.0', f(b'\x01\x00\x01\x00')) |
---|
1106 | n/a | self.assertEqual('170.85.170.85', f(b'\xaa\x55\xaa\x55')) |
---|
1107 | n/a | self.assertEqual('255.255.255.255', f(b'\xff\xff\xff\xff')) |
---|
1108 | n/a | self.assertEqual('1.2.3.4', f(b'\x01\x02\x03\x04')) |
---|
1109 | n/a | assertInvalid(f, b'\x00' * 3) |
---|
1110 | n/a | assertInvalid(f, b'\x00' * 5) |
---|
1111 | n/a | assertInvalid(f, b'\x00' * 16) |
---|
1112 | n/a | self.assertEqual('170.85.170.85', f(bytearray(b'\xaa\x55\xaa\x55'))) |
---|
1113 | n/a | |
---|
1114 | n/a | self.assertEqual('1.0.1.0', g(b'\x01\x00\x01\x00')) |
---|
1115 | n/a | self.assertEqual('170.85.170.85', g(b'\xaa\x55\xaa\x55')) |
---|
1116 | n/a | self.assertEqual('255.255.255.255', g(b'\xff\xff\xff\xff')) |
---|
1117 | n/a | assertInvalid(g, b'\x00' * 3) |
---|
1118 | n/a | assertInvalid(g, b'\x00' * 5) |
---|
1119 | n/a | assertInvalid(g, b'\x00' * 16) |
---|
1120 | n/a | self.assertEqual('170.85.170.85', g(bytearray(b'\xaa\x55\xaa\x55'))) |
---|
1121 | n/a | |
---|
1122 | n/a | @unittest.skipUnless(hasattr(socket, 'inet_ntop'), |
---|
1123 | n/a | 'test needs socket.inet_ntop()') |
---|
1124 | n/a | def testStringToIPv6(self): |
---|
1125 | n/a | try: |
---|
1126 | n/a | from socket import inet_ntop, AF_INET6, has_ipv6 |
---|
1127 | n/a | if not has_ipv6: |
---|
1128 | n/a | self.skipTest('IPv6 not available') |
---|
1129 | n/a | except ImportError: |
---|
1130 | n/a | self.skipTest('could not import needed symbols from socket') |
---|
1131 | n/a | |
---|
1132 | n/a | if sys.platform == "win32": |
---|
1133 | n/a | try: |
---|
1134 | n/a | inet_ntop(AF_INET6, b'\x00' * 16) |
---|
1135 | n/a | except OSError as e: |
---|
1136 | n/a | if e.winerror == 10022: |
---|
1137 | n/a | self.skipTest('IPv6 might not be supported') |
---|
1138 | n/a | |
---|
1139 | n/a | f = lambda a: inet_ntop(AF_INET6, a) |
---|
1140 | n/a | assertInvalid = lambda a: self.assertRaises( |
---|
1141 | n/a | (OSError, ValueError), f, a |
---|
1142 | n/a | ) |
---|
1143 | n/a | |
---|
1144 | n/a | self.assertEqual('::', f(b'\x00' * 16)) |
---|
1145 | n/a | self.assertEqual('::1', f(b'\x00' * 15 + b'\x01')) |
---|
1146 | n/a | self.assertEqual( |
---|
1147 | n/a | 'aef:b01:506:1001:ffff:9997:55:170', |
---|
1148 | n/a | f(b'\x0a\xef\x0b\x01\x05\x06\x10\x01\xff\xff\x99\x97\x00\x55\x01\x70') |
---|
1149 | n/a | ) |
---|
1150 | n/a | self.assertEqual('::1', f(bytearray(b'\x00' * 15 + b'\x01'))) |
---|
1151 | n/a | |
---|
1152 | n/a | assertInvalid(b'\x12' * 15) |
---|
1153 | n/a | assertInvalid(b'\x12' * 17) |
---|
1154 | n/a | assertInvalid(b'\x12' * 4) |
---|
1155 | n/a | |
---|
1156 | n/a | # XXX The following don't test module-level functionality... |
---|
1157 | n/a | |
---|
1158 | n/a | def testSockName(self): |
---|
1159 | n/a | # Testing getsockname() |
---|
1160 | n/a | port = support.find_unused_port() |
---|
1161 | n/a | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
---|
1162 | n/a | self.addCleanup(sock.close) |
---|
1163 | n/a | sock.bind(("0.0.0.0", port)) |
---|
1164 | n/a | name = sock.getsockname() |
---|
1165 | n/a | # XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate |
---|
1166 | n/a | # it reasonable to get the host's addr in addition to 0.0.0.0. |
---|
1167 | n/a | # At least for eCos. This is required for the S/390 to pass. |
---|
1168 | n/a | try: |
---|
1169 | n/a | my_ip_addr = socket.gethostbyname(socket.gethostname()) |
---|
1170 | n/a | except OSError: |
---|
1171 | n/a | # Probably name lookup wasn't set up right; skip this test |
---|
1172 | n/a | self.skipTest('name lookup failure') |
---|
1173 | n/a | self.assertIn(name[0], ("0.0.0.0", my_ip_addr), '%s invalid' % name[0]) |
---|
1174 | n/a | self.assertEqual(name[1], port) |
---|
1175 | n/a | |
---|
1176 | n/a | def testGetSockOpt(self): |
---|
1177 | n/a | # Testing getsockopt() |
---|
1178 | n/a | # We know a socket should start without reuse==0 |
---|
1179 | n/a | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
---|
1180 | n/a | self.addCleanup(sock.close) |
---|
1181 | n/a | reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) |
---|
1182 | n/a | self.assertFalse(reuse != 0, "initial mode is reuse") |
---|
1183 | n/a | |
---|
1184 | n/a | def testSetSockOpt(self): |
---|
1185 | n/a | # Testing setsockopt() |
---|
1186 | n/a | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
---|
1187 | n/a | self.addCleanup(sock.close) |
---|
1188 | n/a | sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
---|
1189 | n/a | reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) |
---|
1190 | n/a | self.assertFalse(reuse == 0, "failed to set reuse mode") |
---|
1191 | n/a | |
---|
1192 | n/a | def testSendAfterClose(self): |
---|
1193 | n/a | # testing send() after close() with timeout |
---|
1194 | n/a | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
---|
1195 | n/a | sock.settimeout(1) |
---|
1196 | n/a | sock.close() |
---|
1197 | n/a | self.assertRaises(OSError, sock.send, b"spam") |
---|
1198 | n/a | |
---|
1199 | n/a | def testCloseException(self): |
---|
1200 | n/a | sock = socket.socket() |
---|
1201 | n/a | socket.socket(fileno=sock.fileno()).close() |
---|
1202 | n/a | try: |
---|
1203 | n/a | sock.close() |
---|
1204 | n/a | except OSError as err: |
---|
1205 | n/a | # Winsock apparently raises ENOTSOCK |
---|
1206 | n/a | self.assertIn(err.errno, (errno.EBADF, errno.ENOTSOCK)) |
---|
1207 | n/a | else: |
---|
1208 | n/a | self.fail("close() should raise EBADF/ENOTSOCK") |
---|
1209 | n/a | |
---|
1210 | n/a | def testNewAttributes(self): |
---|
1211 | n/a | # testing .family, .type and .protocol |
---|
1212 | n/a | |
---|
1213 | n/a | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
---|
1214 | n/a | self.assertEqual(sock.family, socket.AF_INET) |
---|
1215 | n/a | if hasattr(socket, 'SOCK_CLOEXEC'): |
---|
1216 | n/a | self.assertIn(sock.type, |
---|
1217 | n/a | (socket.SOCK_STREAM | socket.SOCK_CLOEXEC, |
---|
1218 | n/a | socket.SOCK_STREAM)) |
---|
1219 | n/a | else: |
---|
1220 | n/a | self.assertEqual(sock.type, socket.SOCK_STREAM) |
---|
1221 | n/a | self.assertEqual(sock.proto, 0) |
---|
1222 | n/a | sock.close() |
---|
1223 | n/a | |
---|
1224 | n/a | def test_getsockaddrarg(self): |
---|
1225 | n/a | sock = socket.socket() |
---|
1226 | n/a | self.addCleanup(sock.close) |
---|
1227 | n/a | port = support.find_unused_port() |
---|
1228 | n/a | big_port = port + 65536 |
---|
1229 | n/a | neg_port = port - 65536 |
---|
1230 | n/a | self.assertRaises(OverflowError, sock.bind, (HOST, big_port)) |
---|
1231 | n/a | self.assertRaises(OverflowError, sock.bind, (HOST, neg_port)) |
---|
1232 | n/a | # Since find_unused_port() is inherently subject to race conditions, we |
---|
1233 | n/a | # call it a couple times if necessary. |
---|
1234 | n/a | for i in itertools.count(): |
---|
1235 | n/a | port = support.find_unused_port() |
---|
1236 | n/a | try: |
---|
1237 | n/a | sock.bind((HOST, port)) |
---|
1238 | n/a | except OSError as e: |
---|
1239 | n/a | if e.errno != errno.EADDRINUSE or i == 5: |
---|
1240 | n/a | raise |
---|
1241 | n/a | else: |
---|
1242 | n/a | break |
---|
1243 | n/a | |
---|
1244 | n/a | @unittest.skipUnless(os.name == "nt", "Windows specific") |
---|
1245 | n/a | def test_sock_ioctl(self): |
---|
1246 | n/a | self.assertTrue(hasattr(socket.socket, 'ioctl')) |
---|
1247 | n/a | self.assertTrue(hasattr(socket, 'SIO_RCVALL')) |
---|
1248 | n/a | self.assertTrue(hasattr(socket, 'RCVALL_ON')) |
---|
1249 | n/a | self.assertTrue(hasattr(socket, 'RCVALL_OFF')) |
---|
1250 | n/a | self.assertTrue(hasattr(socket, 'SIO_KEEPALIVE_VALS')) |
---|
1251 | n/a | s = socket.socket() |
---|
1252 | n/a | self.addCleanup(s.close) |
---|
1253 | n/a | self.assertRaises(ValueError, s.ioctl, -1, None) |
---|
1254 | n/a | s.ioctl(socket.SIO_KEEPALIVE_VALS, (1, 100, 100)) |
---|
1255 | n/a | |
---|
1256 | n/a | @unittest.skipUnless(os.name == "nt", "Windows specific") |
---|
1257 | n/a | @unittest.skipUnless(hasattr(socket, 'SIO_LOOPBACK_FAST_PATH'), |
---|
1258 | n/a | 'Loopback fast path support required for this test') |
---|
1259 | n/a | def test_sio_loopback_fast_path(self): |
---|
1260 | n/a | s = socket.socket() |
---|
1261 | n/a | self.addCleanup(s.close) |
---|
1262 | n/a | try: |
---|
1263 | n/a | s.ioctl(socket.SIO_LOOPBACK_FAST_PATH, True) |
---|
1264 | n/a | except OSError as exc: |
---|
1265 | n/a | WSAEOPNOTSUPP = 10045 |
---|
1266 | n/a | if exc.winerror == WSAEOPNOTSUPP: |
---|
1267 | n/a | self.skipTest("SIO_LOOPBACK_FAST_PATH is defined but " |
---|
1268 | n/a | "doesn't implemented in this Windows version") |
---|
1269 | n/a | raise |
---|
1270 | n/a | self.assertRaises(TypeError, s.ioctl, socket.SIO_LOOPBACK_FAST_PATH, None) |
---|
1271 | n/a | |
---|
1272 | n/a | def testGetaddrinfo(self): |
---|
1273 | n/a | try: |
---|
1274 | n/a | socket.getaddrinfo('localhost', 80) |
---|
1275 | n/a | except socket.gaierror as err: |
---|
1276 | n/a | if err.errno == socket.EAI_SERVICE: |
---|
1277 | n/a | # see http://bugs.python.org/issue1282647 |
---|
1278 | n/a | self.skipTest("buggy libc version") |
---|
1279 | n/a | raise |
---|
1280 | n/a | # len of every sequence is supposed to be == 5 |
---|
1281 | n/a | for info in socket.getaddrinfo(HOST, None): |
---|
1282 | n/a | self.assertEqual(len(info), 5) |
---|
1283 | n/a | # host can be a domain name, a string representation of an |
---|
1284 | n/a | # IPv4/v6 address or None |
---|
1285 | n/a | socket.getaddrinfo('localhost', 80) |
---|
1286 | n/a | socket.getaddrinfo('127.0.0.1', 80) |
---|
1287 | n/a | socket.getaddrinfo(None, 80) |
---|
1288 | n/a | if support.IPV6_ENABLED: |
---|
1289 | n/a | socket.getaddrinfo('::1', 80) |
---|
1290 | n/a | # port can be a string service name such as "http", a numeric |
---|
1291 | n/a | # port number or None |
---|
1292 | n/a | # Issue #26936: Android getaddrinfo() was broken before API level 23. |
---|
1293 | n/a | if (not hasattr(sys, 'getandroidapilevel') or |
---|
1294 | n/a | sys.getandroidapilevel() >= 23): |
---|
1295 | n/a | socket.getaddrinfo(HOST, "http") |
---|
1296 | n/a | socket.getaddrinfo(HOST, 80) |
---|
1297 | n/a | socket.getaddrinfo(HOST, None) |
---|
1298 | n/a | # test family and socktype filters |
---|
1299 | n/a | infos = socket.getaddrinfo(HOST, 80, socket.AF_INET, socket.SOCK_STREAM) |
---|
1300 | n/a | for family, type, _, _, _ in infos: |
---|
1301 | n/a | self.assertEqual(family, socket.AF_INET) |
---|
1302 | n/a | self.assertEqual(str(family), 'AddressFamily.AF_INET') |
---|
1303 | n/a | self.assertEqual(type, socket.SOCK_STREAM) |
---|
1304 | n/a | self.assertEqual(str(type), 'SocketKind.SOCK_STREAM') |
---|
1305 | n/a | infos = socket.getaddrinfo(HOST, None, 0, socket.SOCK_STREAM) |
---|
1306 | n/a | for _, socktype, _, _, _ in infos: |
---|
1307 | n/a | self.assertEqual(socktype, socket.SOCK_STREAM) |
---|
1308 | n/a | # test proto and flags arguments |
---|
1309 | n/a | socket.getaddrinfo(HOST, None, 0, 0, socket.SOL_TCP) |
---|
1310 | n/a | socket.getaddrinfo(HOST, None, 0, 0, 0, socket.AI_PASSIVE) |
---|
1311 | n/a | # a server willing to support both IPv4 and IPv6 will |
---|
1312 | n/a | # usually do this |
---|
1313 | n/a | socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, |
---|
1314 | n/a | socket.AI_PASSIVE) |
---|
1315 | n/a | # test keyword arguments |
---|
1316 | n/a | a = socket.getaddrinfo(HOST, None) |
---|
1317 | n/a | b = socket.getaddrinfo(host=HOST, port=None) |
---|
1318 | n/a | self.assertEqual(a, b) |
---|
1319 | n/a | a = socket.getaddrinfo(HOST, None, socket.AF_INET) |
---|
1320 | n/a | b = socket.getaddrinfo(HOST, None, family=socket.AF_INET) |
---|
1321 | n/a | self.assertEqual(a, b) |
---|
1322 | n/a | a = socket.getaddrinfo(HOST, None, 0, socket.SOCK_STREAM) |
---|
1323 | n/a | b = socket.getaddrinfo(HOST, None, type=socket.SOCK_STREAM) |
---|
1324 | n/a | self.assertEqual(a, b) |
---|
1325 | n/a | a = socket.getaddrinfo(HOST, None, 0, 0, socket.SOL_TCP) |
---|
1326 | n/a | b = socket.getaddrinfo(HOST, None, proto=socket.SOL_TCP) |
---|
1327 | n/a | self.assertEqual(a, b) |
---|
1328 | n/a | a = socket.getaddrinfo(HOST, None, 0, 0, 0, socket.AI_PASSIVE) |
---|
1329 | n/a | b = socket.getaddrinfo(HOST, None, flags=socket.AI_PASSIVE) |
---|
1330 | n/a | self.assertEqual(a, b) |
---|
1331 | n/a | a = socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, |
---|
1332 | n/a | socket.AI_PASSIVE) |
---|
1333 | n/a | b = socket.getaddrinfo(host=None, port=0, family=socket.AF_UNSPEC, |
---|
1334 | n/a | type=socket.SOCK_STREAM, proto=0, |
---|
1335 | n/a | flags=socket.AI_PASSIVE) |
---|
1336 | n/a | self.assertEqual(a, b) |
---|
1337 | n/a | # Issue #6697. |
---|
1338 | n/a | self.assertRaises(UnicodeEncodeError, socket.getaddrinfo, 'localhost', '\uD800') |
---|
1339 | n/a | |
---|
1340 | n/a | # Issue 17269: test workaround for OS X platform bug segfault |
---|
1341 | n/a | if hasattr(socket, 'AI_NUMERICSERV'): |
---|
1342 | n/a | try: |
---|
1343 | n/a | # The arguments here are undefined and the call may succeed |
---|
1344 | n/a | # or fail. All we care here is that it doesn't segfault. |
---|
1345 | n/a | socket.getaddrinfo("localhost", None, 0, 0, 0, |
---|
1346 | n/a | socket.AI_NUMERICSERV) |
---|
1347 | n/a | except socket.gaierror: |
---|
1348 | n/a | pass |
---|
1349 | n/a | |
---|
1350 | n/a | def test_getnameinfo(self): |
---|
1351 | n/a | # only IP addresses are allowed |
---|
1352 | n/a | self.assertRaises(OSError, socket.getnameinfo, ('mail.python.org',0), 0) |
---|
1353 | n/a | |
---|
1354 | n/a | @unittest.skipUnless(support.is_resource_enabled('network'), |
---|
1355 | n/a | 'network is not enabled') |
---|
1356 | n/a | def test_idna(self): |
---|
1357 | n/a | # Check for internet access before running test |
---|
1358 | n/a | # (issue #12804, issue #25138). |
---|
1359 | n/a | with support.transient_internet('python.org'): |
---|
1360 | n/a | socket.gethostbyname('python.org') |
---|
1361 | n/a | |
---|
1362 | n/a | # these should all be successful |
---|
1363 | n/a | domain = 'รยธรรยฟรรรยฐรยฝรยธรยต.pythontest.net' |
---|
1364 | n/a | socket.gethostbyname(domain) |
---|
1365 | n/a | socket.gethostbyname_ex(domain) |
---|
1366 | n/a | socket.getaddrinfo(domain,0,socket.AF_UNSPEC,socket.SOCK_STREAM) |
---|
1367 | n/a | # this may not work if the forward lookup choses the IPv6 address, as that doesn't |
---|
1368 | n/a | # have a reverse entry yet |
---|
1369 | n/a | # socket.gethostbyaddr('รยธรรยฟรรรยฐรยฝรยธรยต.python.org') |
---|
1370 | n/a | |
---|
1371 | n/a | def check_sendall_interrupted(self, with_timeout): |
---|
1372 | n/a | # socketpair() is not strictly required, but it makes things easier. |
---|
1373 | n/a | if not hasattr(signal, 'alarm') or not hasattr(socket, 'socketpair'): |
---|
1374 | n/a | self.skipTest("signal.alarm and socket.socketpair required for this test") |
---|
1375 | n/a | # Our signal handlers clobber the C errno by calling a math function |
---|
1376 | n/a | # with an invalid domain value. |
---|
1377 | n/a | def ok_handler(*args): |
---|
1378 | n/a | self.assertRaises(ValueError, math.acosh, 0) |
---|
1379 | n/a | def raising_handler(*args): |
---|
1380 | n/a | self.assertRaises(ValueError, math.acosh, 0) |
---|
1381 | n/a | 1 // 0 |
---|
1382 | n/a | c, s = socket.socketpair() |
---|
1383 | n/a | old_alarm = signal.signal(signal.SIGALRM, raising_handler) |
---|
1384 | n/a | try: |
---|
1385 | n/a | if with_timeout: |
---|
1386 | n/a | # Just above the one second minimum for signal.alarm |
---|
1387 | n/a | c.settimeout(1.5) |
---|
1388 | n/a | with self.assertRaises(ZeroDivisionError): |
---|
1389 | n/a | signal.alarm(1) |
---|
1390 | n/a | c.sendall(b"x" * support.SOCK_MAX_SIZE) |
---|
1391 | n/a | if with_timeout: |
---|
1392 | n/a | signal.signal(signal.SIGALRM, ok_handler) |
---|
1393 | n/a | signal.alarm(1) |
---|
1394 | n/a | self.assertRaises(socket.timeout, c.sendall, |
---|
1395 | n/a | b"x" * support.SOCK_MAX_SIZE) |
---|
1396 | n/a | finally: |
---|
1397 | n/a | signal.alarm(0) |
---|
1398 | n/a | signal.signal(signal.SIGALRM, old_alarm) |
---|
1399 | n/a | c.close() |
---|
1400 | n/a | s.close() |
---|
1401 | n/a | |
---|
1402 | n/a | def test_sendall_interrupted(self): |
---|
1403 | n/a | self.check_sendall_interrupted(False) |
---|
1404 | n/a | |
---|
1405 | n/a | def test_sendall_interrupted_with_timeout(self): |
---|
1406 | n/a | self.check_sendall_interrupted(True) |
---|
1407 | n/a | |
---|
1408 | n/a | def test_dealloc_warn(self): |
---|
1409 | n/a | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
---|
1410 | n/a | r = repr(sock) |
---|
1411 | n/a | with self.assertWarns(ResourceWarning) as cm: |
---|
1412 | n/a | sock = None |
---|
1413 | n/a | support.gc_collect() |
---|
1414 | n/a | self.assertIn(r, str(cm.warning.args[0])) |
---|
1415 | n/a | # An open socket file object gets dereferenced after the socket |
---|
1416 | n/a | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
---|
1417 | n/a | f = sock.makefile('rb') |
---|
1418 | n/a | r = repr(sock) |
---|
1419 | n/a | sock = None |
---|
1420 | n/a | support.gc_collect() |
---|
1421 | n/a | with self.assertWarns(ResourceWarning): |
---|
1422 | n/a | f = None |
---|
1423 | n/a | support.gc_collect() |
---|
1424 | n/a | |
---|
1425 | n/a | def test_name_closed_socketio(self): |
---|
1426 | n/a | with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: |
---|
1427 | n/a | fp = sock.makefile("rb") |
---|
1428 | n/a | fp.close() |
---|
1429 | n/a | self.assertEqual(repr(fp), "<_io.BufferedReader name=-1>") |
---|
1430 | n/a | |
---|
1431 | n/a | def test_unusable_closed_socketio(self): |
---|
1432 | n/a | with socket.socket() as sock: |
---|
1433 | n/a | fp = sock.makefile("rb", buffering=0) |
---|
1434 | n/a | self.assertTrue(fp.readable()) |
---|
1435 | n/a | self.assertFalse(fp.writable()) |
---|
1436 | n/a | self.assertFalse(fp.seekable()) |
---|
1437 | n/a | fp.close() |
---|
1438 | n/a | self.assertRaises(ValueError, fp.readable) |
---|
1439 | n/a | self.assertRaises(ValueError, fp.writable) |
---|
1440 | n/a | self.assertRaises(ValueError, fp.seekable) |
---|
1441 | n/a | |
---|
1442 | n/a | def test_makefile_mode(self): |
---|
1443 | n/a | for mode in 'r', 'rb', 'rw', 'w', 'wb': |
---|
1444 | n/a | with self.subTest(mode=mode): |
---|
1445 | n/a | with socket.socket() as sock: |
---|
1446 | n/a | with sock.makefile(mode) as fp: |
---|
1447 | n/a | self.assertEqual(fp.mode, mode) |
---|
1448 | n/a | |
---|
1449 | n/a | def test_makefile_invalid_mode(self): |
---|
1450 | n/a | for mode in 'rt', 'x', '+', 'a': |
---|
1451 | n/a | with self.subTest(mode=mode): |
---|
1452 | n/a | with socket.socket() as sock: |
---|
1453 | n/a | with self.assertRaisesRegex(ValueError, 'invalid mode'): |
---|
1454 | n/a | sock.makefile(mode) |
---|
1455 | n/a | |
---|
1456 | n/a | def test_pickle(self): |
---|
1457 | n/a | sock = socket.socket() |
---|
1458 | n/a | with sock: |
---|
1459 | n/a | for protocol in range(pickle.HIGHEST_PROTOCOL + 1): |
---|
1460 | n/a | self.assertRaises(TypeError, pickle.dumps, sock, protocol) |
---|
1461 | n/a | for protocol in range(pickle.HIGHEST_PROTOCOL + 1): |
---|
1462 | n/a | family = pickle.loads(pickle.dumps(socket.AF_INET, protocol)) |
---|
1463 | n/a | self.assertEqual(family, socket.AF_INET) |
---|
1464 | n/a | type = pickle.loads(pickle.dumps(socket.SOCK_STREAM, protocol)) |
---|
1465 | n/a | self.assertEqual(type, socket.SOCK_STREAM) |
---|
1466 | n/a | |
---|
1467 | n/a | def test_listen_backlog(self): |
---|
1468 | n/a | for backlog in 0, -1: |
---|
1469 | n/a | with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as srv: |
---|
1470 | n/a | srv.bind((HOST, 0)) |
---|
1471 | n/a | srv.listen(backlog) |
---|
1472 | n/a | |
---|
1473 | n/a | with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as srv: |
---|
1474 | n/a | srv.bind((HOST, 0)) |
---|
1475 | n/a | srv.listen() |
---|
1476 | n/a | |
---|
1477 | n/a | @support.cpython_only |
---|
1478 | n/a | def test_listen_backlog_overflow(self): |
---|
1479 | n/a | # Issue 15989 |
---|
1480 | n/a | import _testcapi |
---|
1481 | n/a | srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
---|
1482 | n/a | srv.bind((HOST, 0)) |
---|
1483 | n/a | self.assertRaises(OverflowError, srv.listen, _testcapi.INT_MAX + 1) |
---|
1484 | n/a | srv.close() |
---|
1485 | n/a | |
---|
1486 | n/a | @unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.') |
---|
1487 | n/a | def test_flowinfo(self): |
---|
1488 | n/a | self.assertRaises(OverflowError, socket.getnameinfo, |
---|
1489 | n/a | (support.HOSTv6, 0, 0xffffffff), 0) |
---|
1490 | n/a | with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s: |
---|
1491 | n/a | self.assertRaises(OverflowError, s.bind, (support.HOSTv6, 0, -10)) |
---|
1492 | n/a | |
---|
1493 | n/a | def test_str_for_enums(self): |
---|
1494 | n/a | # Make sure that the AF_* and SOCK_* constants have enum-like string |
---|
1495 | n/a | # reprs. |
---|
1496 | n/a | with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: |
---|
1497 | n/a | self.assertEqual(str(s.family), 'AddressFamily.AF_INET') |
---|
1498 | n/a | self.assertEqual(str(s.type), 'SocketKind.SOCK_STREAM') |
---|
1499 | n/a | |
---|
1500 | n/a | @unittest.skipIf(os.name == 'nt', 'Will not work on Windows') |
---|
1501 | n/a | def test_uknown_socket_family_repr(self): |
---|
1502 | n/a | # Test that when created with a family that's not one of the known |
---|
1503 | n/a | # AF_*/SOCK_* constants, socket.family just returns the number. |
---|
1504 | n/a | # |
---|
1505 | n/a | # To do this we fool socket.socket into believing it already has an |
---|
1506 | n/a | # open fd because on this path it doesn't actually verify the family and |
---|
1507 | n/a | # type and populates the socket object. |
---|
1508 | n/a | # |
---|
1509 | n/a | # On Windows this trick won't work, so the test is skipped. |
---|
1510 | n/a | fd, path = tempfile.mkstemp() |
---|
1511 | n/a | self.addCleanup(os.unlink, path) |
---|
1512 | n/a | with socket.socket(family=42424, type=13331, fileno=fd) as s: |
---|
1513 | n/a | self.assertEqual(s.family, 42424) |
---|
1514 | n/a | self.assertEqual(s.type, 13331) |
---|
1515 | n/a | |
---|
1516 | n/a | @unittest.skipUnless(hasattr(os, 'sendfile'), 'test needs os.sendfile()') |
---|
1517 | n/a | def test__sendfile_use_sendfile(self): |
---|
1518 | n/a | class File: |
---|
1519 | n/a | def __init__(self, fd): |
---|
1520 | n/a | self.fd = fd |
---|
1521 | n/a | |
---|
1522 | n/a | def fileno(self): |
---|
1523 | n/a | return self.fd |
---|
1524 | n/a | with socket.socket() as sock: |
---|
1525 | n/a | fd = os.open(os.curdir, os.O_RDONLY) |
---|
1526 | n/a | os.close(fd) |
---|
1527 | n/a | with self.assertRaises(socket._GiveupOnSendfile): |
---|
1528 | n/a | sock._sendfile_use_sendfile(File(fd)) |
---|
1529 | n/a | with self.assertRaises(OverflowError): |
---|
1530 | n/a | sock._sendfile_use_sendfile(File(2**1000)) |
---|
1531 | n/a | with self.assertRaises(TypeError): |
---|
1532 | n/a | sock._sendfile_use_sendfile(File(None)) |
---|
1533 | n/a | |
---|
1534 | n/a | |
---|
1535 | n/a | @unittest.skipUnless(HAVE_SOCKET_CAN, 'SocketCan required for this test.') |
---|
1536 | n/a | class BasicCANTest(unittest.TestCase): |
---|
1537 | n/a | |
---|
1538 | n/a | def testCrucialConstants(self): |
---|
1539 | n/a | socket.AF_CAN |
---|
1540 | n/a | socket.PF_CAN |
---|
1541 | n/a | socket.CAN_RAW |
---|
1542 | n/a | |
---|
1543 | n/a | @unittest.skipUnless(hasattr(socket, "CAN_BCM"), |
---|
1544 | n/a | 'socket.CAN_BCM required for this test.') |
---|
1545 | n/a | def testBCMConstants(self): |
---|
1546 | n/a | socket.CAN_BCM |
---|
1547 | n/a | |
---|
1548 | n/a | # opcodes |
---|
1549 | n/a | socket.CAN_BCM_TX_SETUP # create (cyclic) transmission task |
---|
1550 | n/a | socket.CAN_BCM_TX_DELETE # remove (cyclic) transmission task |
---|
1551 | n/a | socket.CAN_BCM_TX_READ # read properties of (cyclic) transmission task |
---|
1552 | n/a | socket.CAN_BCM_TX_SEND # send one CAN frame |
---|
1553 | n/a | socket.CAN_BCM_RX_SETUP # create RX content filter subscription |
---|
1554 | n/a | socket.CAN_BCM_RX_DELETE # remove RX content filter subscription |
---|
1555 | n/a | socket.CAN_BCM_RX_READ # read properties of RX content filter subscription |
---|
1556 | n/a | socket.CAN_BCM_TX_STATUS # reply to TX_READ request |
---|
1557 | n/a | socket.CAN_BCM_TX_EXPIRED # notification on performed transmissions (count=0) |
---|
1558 | n/a | socket.CAN_BCM_RX_STATUS # reply to RX_READ request |
---|
1559 | n/a | socket.CAN_BCM_RX_TIMEOUT # cyclic message is absent |
---|
1560 | n/a | socket.CAN_BCM_RX_CHANGED # updated CAN frame (detected content change) |
---|
1561 | n/a | |
---|
1562 | n/a | def testCreateSocket(self): |
---|
1563 | n/a | with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s: |
---|
1564 | n/a | pass |
---|
1565 | n/a | |
---|
1566 | n/a | @unittest.skipUnless(hasattr(socket, "CAN_BCM"), |
---|
1567 | n/a | 'socket.CAN_BCM required for this test.') |
---|
1568 | n/a | def testCreateBCMSocket(self): |
---|
1569 | n/a | with socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_BCM) as s: |
---|
1570 | n/a | pass |
---|
1571 | n/a | |
---|
1572 | n/a | def testBindAny(self): |
---|
1573 | n/a | with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s: |
---|
1574 | n/a | s.bind(('', )) |
---|
1575 | n/a | |
---|
1576 | n/a | def testTooLongInterfaceName(self): |
---|
1577 | n/a | # most systems limit IFNAMSIZ to 16, take 1024 to be sure |
---|
1578 | n/a | with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s: |
---|
1579 | n/a | self.assertRaisesRegex(OSError, 'interface name too long', |
---|
1580 | n/a | s.bind, ('x' * 1024,)) |
---|
1581 | n/a | |
---|
1582 | n/a | @unittest.skipUnless(hasattr(socket, "CAN_RAW_LOOPBACK"), |
---|
1583 | n/a | 'socket.CAN_RAW_LOOPBACK required for this test.') |
---|
1584 | n/a | def testLoopback(self): |
---|
1585 | n/a | with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s: |
---|
1586 | n/a | for loopback in (0, 1): |
---|
1587 | n/a | s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_LOOPBACK, |
---|
1588 | n/a | loopback) |
---|
1589 | n/a | self.assertEqual(loopback, |
---|
1590 | n/a | s.getsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_LOOPBACK)) |
---|
1591 | n/a | |
---|
1592 | n/a | @unittest.skipUnless(hasattr(socket, "CAN_RAW_FILTER"), |
---|
1593 | n/a | 'socket.CAN_RAW_FILTER required for this test.') |
---|
1594 | n/a | def testFilter(self): |
---|
1595 | n/a | can_id, can_mask = 0x200, 0x700 |
---|
1596 | n/a | can_filter = struct.pack("=II", can_id, can_mask) |
---|
1597 | n/a | with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s: |
---|
1598 | n/a | s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FILTER, can_filter) |
---|
1599 | n/a | self.assertEqual(can_filter, |
---|
1600 | n/a | s.getsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FILTER, 8)) |
---|
1601 | n/a | s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FILTER, bytearray(can_filter)) |
---|
1602 | n/a | |
---|
1603 | n/a | |
---|
1604 | n/a | @unittest.skipUnless(HAVE_SOCKET_CAN, 'SocketCan required for this test.') |
---|
1605 | n/a | @unittest.skipUnless(thread, 'Threading required for this test.') |
---|
1606 | n/a | class CANTest(ThreadedCANSocketTest): |
---|
1607 | n/a | |
---|
1608 | n/a | def __init__(self, methodName='runTest'): |
---|
1609 | n/a | ThreadedCANSocketTest.__init__(self, methodName=methodName) |
---|
1610 | n/a | |
---|
1611 | n/a | @classmethod |
---|
1612 | n/a | def build_can_frame(cls, can_id, data): |
---|
1613 | n/a | """Build a CAN frame.""" |
---|
1614 | n/a | can_dlc = len(data) |
---|
1615 | n/a | data = data.ljust(8, b'\x00') |
---|
1616 | n/a | return struct.pack(cls.can_frame_fmt, can_id, can_dlc, data) |
---|
1617 | n/a | |
---|
1618 | n/a | @classmethod |
---|
1619 | n/a | def dissect_can_frame(cls, frame): |
---|
1620 | n/a | """Dissect a CAN frame.""" |
---|
1621 | n/a | can_id, can_dlc, data = struct.unpack(cls.can_frame_fmt, frame) |
---|
1622 | n/a | return (can_id, can_dlc, data[:can_dlc]) |
---|
1623 | n/a | |
---|
1624 | n/a | def testSendFrame(self): |
---|
1625 | n/a | cf, addr = self.s.recvfrom(self.bufsize) |
---|
1626 | n/a | self.assertEqual(self.cf, cf) |
---|
1627 | n/a | self.assertEqual(addr[0], self.interface) |
---|
1628 | n/a | self.assertEqual(addr[1], socket.AF_CAN) |
---|
1629 | n/a | |
---|
1630 | n/a | def _testSendFrame(self): |
---|
1631 | n/a | self.cf = self.build_can_frame(0x00, b'\x01\x02\x03\x04\x05') |
---|
1632 | n/a | self.cli.send(self.cf) |
---|
1633 | n/a | |
---|
1634 | n/a | def testSendMaxFrame(self): |
---|
1635 | n/a | cf, addr = self.s.recvfrom(self.bufsize) |
---|
1636 | n/a | self.assertEqual(self.cf, cf) |
---|
1637 | n/a | |
---|
1638 | n/a | def _testSendMaxFrame(self): |
---|
1639 | n/a | self.cf = self.build_can_frame(0x00, b'\x07' * 8) |
---|
1640 | n/a | self.cli.send(self.cf) |
---|
1641 | n/a | |
---|
1642 | n/a | def testSendMultiFrames(self): |
---|
1643 | n/a | cf, addr = self.s.recvfrom(self.bufsize) |
---|
1644 | n/a | self.assertEqual(self.cf1, cf) |
---|
1645 | n/a | |
---|
1646 | n/a | cf, addr = self.s.recvfrom(self.bufsize) |
---|
1647 | n/a | self.assertEqual(self.cf2, cf) |
---|
1648 | n/a | |
---|
1649 | n/a | def _testSendMultiFrames(self): |
---|
1650 | n/a | self.cf1 = self.build_can_frame(0x07, b'\x44\x33\x22\x11') |
---|
1651 | n/a | self.cli.send(self.cf1) |
---|
1652 | n/a | |
---|
1653 | n/a | self.cf2 = self.build_can_frame(0x12, b'\x99\x22\x33') |
---|
1654 | n/a | self.cli.send(self.cf2) |
---|
1655 | n/a | |
---|
1656 | n/a | @unittest.skipUnless(hasattr(socket, "CAN_BCM"), |
---|
1657 | n/a | 'socket.CAN_BCM required for this test.') |
---|
1658 | n/a | def _testBCM(self): |
---|
1659 | n/a | cf, addr = self.cli.recvfrom(self.bufsize) |
---|
1660 | n/a | self.assertEqual(self.cf, cf) |
---|
1661 | n/a | can_id, can_dlc, data = self.dissect_can_frame(cf) |
---|
1662 | n/a | self.assertEqual(self.can_id, can_id) |
---|
1663 | n/a | self.assertEqual(self.data, data) |
---|
1664 | n/a | |
---|
1665 | n/a | @unittest.skipUnless(hasattr(socket, "CAN_BCM"), |
---|
1666 | n/a | 'socket.CAN_BCM required for this test.') |
---|
1667 | n/a | def testBCM(self): |
---|
1668 | n/a | bcm = socket.socket(socket.PF_CAN, socket.SOCK_DGRAM, socket.CAN_BCM) |
---|
1669 | n/a | self.addCleanup(bcm.close) |
---|
1670 | n/a | bcm.connect((self.interface,)) |
---|
1671 | n/a | self.can_id = 0x123 |
---|
1672 | n/a | self.data = bytes([0xc0, 0xff, 0xee]) |
---|
1673 | n/a | self.cf = self.build_can_frame(self.can_id, self.data) |
---|
1674 | n/a | opcode = socket.CAN_BCM_TX_SEND |
---|
1675 | n/a | flags = 0 |
---|
1676 | n/a | count = 0 |
---|
1677 | n/a | ival1_seconds = ival1_usec = ival2_seconds = ival2_usec = 0 |
---|
1678 | n/a | bcm_can_id = 0x0222 |
---|
1679 | n/a | nframes = 1 |
---|
1680 | n/a | assert len(self.cf) == 16 |
---|
1681 | n/a | header = struct.pack(self.bcm_cmd_msg_fmt, |
---|
1682 | n/a | opcode, |
---|
1683 | n/a | flags, |
---|
1684 | n/a | count, |
---|
1685 | n/a | ival1_seconds, |
---|
1686 | n/a | ival1_usec, |
---|
1687 | n/a | ival2_seconds, |
---|
1688 | n/a | ival2_usec, |
---|
1689 | n/a | bcm_can_id, |
---|
1690 | n/a | nframes, |
---|
1691 | n/a | ) |
---|
1692 | n/a | header_plus_frame = header + self.cf |
---|
1693 | n/a | bytes_sent = bcm.send(header_plus_frame) |
---|
1694 | n/a | self.assertEqual(bytes_sent, len(header_plus_frame)) |
---|
1695 | n/a | |
---|
1696 | n/a | |
---|
1697 | n/a | @unittest.skipUnless(HAVE_SOCKET_RDS, 'RDS sockets required for this test.') |
---|
1698 | n/a | class BasicRDSTest(unittest.TestCase): |
---|
1699 | n/a | |
---|
1700 | n/a | def testCrucialConstants(self): |
---|
1701 | n/a | socket.AF_RDS |
---|
1702 | n/a | socket.PF_RDS |
---|
1703 | n/a | |
---|
1704 | n/a | def testCreateSocket(self): |
---|
1705 | n/a | with socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0) as s: |
---|
1706 | n/a | pass |
---|
1707 | n/a | |
---|
1708 | n/a | def testSocketBufferSize(self): |
---|
1709 | n/a | bufsize = 16384 |
---|
1710 | n/a | with socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0) as s: |
---|
1711 | n/a | s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, bufsize) |
---|
1712 | n/a | s.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, bufsize) |
---|
1713 | n/a | |
---|
1714 | n/a | |
---|
1715 | n/a | @unittest.skipUnless(HAVE_SOCKET_RDS, 'RDS sockets required for this test.') |
---|
1716 | n/a | @unittest.skipUnless(thread, 'Threading required for this test.') |
---|
1717 | n/a | class RDSTest(ThreadedRDSSocketTest): |
---|
1718 | n/a | |
---|
1719 | n/a | def __init__(self, methodName='runTest'): |
---|
1720 | n/a | ThreadedRDSSocketTest.__init__(self, methodName=methodName) |
---|
1721 | n/a | |
---|
1722 | n/a | def setUp(self): |
---|
1723 | n/a | super().setUp() |
---|
1724 | n/a | self.evt = threading.Event() |
---|
1725 | n/a | |
---|
1726 | n/a | def testSendAndRecv(self): |
---|
1727 | n/a | data, addr = self.serv.recvfrom(self.bufsize) |
---|
1728 | n/a | self.assertEqual(self.data, data) |
---|
1729 | n/a | self.assertEqual(self.cli_addr, addr) |
---|
1730 | n/a | |
---|
1731 | n/a | def _testSendAndRecv(self): |
---|
1732 | n/a | self.data = b'spam' |
---|
1733 | n/a | self.cli.sendto(self.data, 0, (HOST, self.port)) |
---|
1734 | n/a | |
---|
1735 | n/a | def testPeek(self): |
---|
1736 | n/a | data, addr = self.serv.recvfrom(self.bufsize, socket.MSG_PEEK) |
---|
1737 | n/a | self.assertEqual(self.data, data) |
---|
1738 | n/a | data, addr = self.serv.recvfrom(self.bufsize) |
---|
1739 | n/a | self.assertEqual(self.data, data) |
---|
1740 | n/a | |
---|
1741 | n/a | def _testPeek(self): |
---|
1742 | n/a | self.data = b'spam' |
---|
1743 | n/a | self.cli.sendto(self.data, 0, (HOST, self.port)) |
---|
1744 | n/a | |
---|
1745 | n/a | @requireAttrs(socket.socket, 'recvmsg') |
---|
1746 | n/a | def testSendAndRecvMsg(self): |
---|
1747 | n/a | data, ancdata, msg_flags, addr = self.serv.recvmsg(self.bufsize) |
---|
1748 | n/a | self.assertEqual(self.data, data) |
---|
1749 | n/a | |
---|
1750 | n/a | @requireAttrs(socket.socket, 'sendmsg') |
---|
1751 | n/a | def _testSendAndRecvMsg(self): |
---|
1752 | n/a | self.data = b'hello ' * 10 |
---|
1753 | n/a | self.cli.sendmsg([self.data], (), 0, (HOST, self.port)) |
---|
1754 | n/a | |
---|
1755 | n/a | def testSendAndRecvMulti(self): |
---|
1756 | n/a | data, addr = self.serv.recvfrom(self.bufsize) |
---|
1757 | n/a | self.assertEqual(self.data1, data) |
---|
1758 | n/a | |
---|
1759 | n/a | data, addr = self.serv.recvfrom(self.bufsize) |
---|
1760 | n/a | self.assertEqual(self.data2, data) |
---|
1761 | n/a | |
---|
1762 | n/a | def _testSendAndRecvMulti(self): |
---|
1763 | n/a | self.data1 = b'bacon' |
---|
1764 | n/a | self.cli.sendto(self.data1, 0, (HOST, self.port)) |
---|
1765 | n/a | |
---|
1766 | n/a | self.data2 = b'egg' |
---|
1767 | n/a | self.cli.sendto(self.data2, 0, (HOST, self.port)) |
---|
1768 | n/a | |
---|
1769 | n/a | def testSelect(self): |
---|
1770 | n/a | r, w, x = select.select([self.serv], [], [], 3.0) |
---|
1771 | n/a | self.assertIn(self.serv, r) |
---|
1772 | n/a | data, addr = self.serv.recvfrom(self.bufsize) |
---|
1773 | n/a | self.assertEqual(self.data, data) |
---|
1774 | n/a | |
---|
1775 | n/a | def _testSelect(self): |
---|
1776 | n/a | self.data = b'select' |
---|
1777 | n/a | self.cli.sendto(self.data, 0, (HOST, self.port)) |
---|
1778 | n/a | |
---|
1779 | n/a | def testCongestion(self): |
---|
1780 | n/a | # wait until the sender is done |
---|
1781 | n/a | self.evt.wait() |
---|
1782 | n/a | |
---|
1783 | n/a | def _testCongestion(self): |
---|
1784 | n/a | # test the behavior in case of congestion |
---|
1785 | n/a | self.data = b'fill' |
---|
1786 | n/a | self.cli.setblocking(False) |
---|
1787 | n/a | try: |
---|
1788 | n/a | # try to lower the receiver's socket buffer size |
---|
1789 | n/a | self.cli.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 16384) |
---|
1790 | n/a | except OSError: |
---|
1791 | n/a | pass |
---|
1792 | n/a | with self.assertRaises(OSError) as cm: |
---|
1793 | n/a | try: |
---|
1794 | n/a | # fill the receiver's socket buffer |
---|
1795 | n/a | while True: |
---|
1796 | n/a | self.cli.sendto(self.data, 0, (HOST, self.port)) |
---|
1797 | n/a | finally: |
---|
1798 | n/a | # signal the receiver we're done |
---|
1799 | n/a | self.evt.set() |
---|
1800 | n/a | # sendto() should have failed with ENOBUFS |
---|
1801 | n/a | self.assertEqual(cm.exception.errno, errno.ENOBUFS) |
---|
1802 | n/a | # and we should have received a congestion notification through poll |
---|
1803 | n/a | r, w, x = select.select([self.serv], [], [], 3.0) |
---|
1804 | n/a | self.assertIn(self.serv, r) |
---|
1805 | n/a | |
---|
1806 | n/a | |
---|
1807 | n/a | @unittest.skipUnless(thread, 'Threading required for this test.') |
---|
1808 | n/a | class BasicTCPTest(SocketConnectedTest): |
---|
1809 | n/a | |
---|
1810 | n/a | def __init__(self, methodName='runTest'): |
---|
1811 | n/a | SocketConnectedTest.__init__(self, methodName=methodName) |
---|
1812 | n/a | |
---|
1813 | n/a | def testRecv(self): |
---|
1814 | n/a | # Testing large receive over TCP |
---|
1815 | n/a | msg = self.cli_conn.recv(1024) |
---|
1816 | n/a | self.assertEqual(msg, MSG) |
---|
1817 | n/a | |
---|
1818 | n/a | def _testRecv(self): |
---|
1819 | n/a | self.serv_conn.send(MSG) |
---|
1820 | n/a | |
---|
1821 | n/a | def testOverFlowRecv(self): |
---|
1822 | n/a | # Testing receive in chunks over TCP |
---|
1823 | n/a | seg1 = self.cli_conn.recv(len(MSG) - 3) |
---|
1824 | n/a | seg2 = self.cli_conn.recv(1024) |
---|
1825 | n/a | msg = seg1 + seg2 |
---|
1826 | n/a | self.assertEqual(msg, MSG) |
---|
1827 | n/a | |
---|
1828 | n/a | def _testOverFlowRecv(self): |
---|
1829 | n/a | self.serv_conn.send(MSG) |
---|
1830 | n/a | |
---|
1831 | n/a | def testRecvFrom(self): |
---|
1832 | n/a | # Testing large recvfrom() over TCP |
---|
1833 | n/a | msg, addr = self.cli_conn.recvfrom(1024) |
---|
1834 | n/a | self.assertEqual(msg, MSG) |
---|
1835 | n/a | |
---|
1836 | n/a | def _testRecvFrom(self): |
---|
1837 | n/a | self.serv_conn.send(MSG) |
---|
1838 | n/a | |
---|
1839 | n/a | def testOverFlowRecvFrom(self): |
---|
1840 | n/a | # Testing recvfrom() in chunks over TCP |
---|
1841 | n/a | seg1, addr = self.cli_conn.recvfrom(len(MSG)-3) |
---|
1842 | n/a | seg2, addr = self.cli_conn.recvfrom(1024) |
---|
1843 | n/a | msg = seg1 + seg2 |
---|
1844 | n/a | self.assertEqual(msg, MSG) |
---|
1845 | n/a | |
---|
1846 | n/a | def _testOverFlowRecvFrom(self): |
---|
1847 | n/a | self.serv_conn.send(MSG) |
---|
1848 | n/a | |
---|
1849 | n/a | def testSendAll(self): |
---|
1850 | n/a | # Testing sendall() with a 2048 byte string over TCP |
---|
1851 | n/a | msg = b'' |
---|
1852 | n/a | while 1: |
---|
1853 | n/a | read = self.cli_conn.recv(1024) |
---|
1854 | n/a | if not read: |
---|
1855 | n/a | break |
---|
1856 | n/a | msg += read |
---|
1857 | n/a | self.assertEqual(msg, b'f' * 2048) |
---|
1858 | n/a | |
---|
1859 | n/a | def _testSendAll(self): |
---|
1860 | n/a | big_chunk = b'f' * 2048 |
---|
1861 | n/a | self.serv_conn.sendall(big_chunk) |
---|
1862 | n/a | |
---|
1863 | n/a | def testFromFd(self): |
---|
1864 | n/a | # Testing fromfd() |
---|
1865 | n/a | fd = self.cli_conn.fileno() |
---|
1866 | n/a | sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM) |
---|
1867 | n/a | self.addCleanup(sock.close) |
---|
1868 | n/a | self.assertIsInstance(sock, socket.socket) |
---|
1869 | n/a | msg = sock.recv(1024) |
---|
1870 | n/a | self.assertEqual(msg, MSG) |
---|
1871 | n/a | |
---|
1872 | n/a | def _testFromFd(self): |
---|
1873 | n/a | self.serv_conn.send(MSG) |
---|
1874 | n/a | |
---|
1875 | n/a | def testDup(self): |
---|
1876 | n/a | # Testing dup() |
---|
1877 | n/a | sock = self.cli_conn.dup() |
---|
1878 | n/a | self.addCleanup(sock.close) |
---|
1879 | n/a | msg = sock.recv(1024) |
---|
1880 | n/a | self.assertEqual(msg, MSG) |
---|
1881 | n/a | |
---|
1882 | n/a | def _testDup(self): |
---|
1883 | n/a | self.serv_conn.send(MSG) |
---|
1884 | n/a | |
---|
1885 | n/a | def testShutdown(self): |
---|
1886 | n/a | # Testing shutdown() |
---|
1887 | n/a | msg = self.cli_conn.recv(1024) |
---|
1888 | n/a | self.assertEqual(msg, MSG) |
---|
1889 | n/a | # wait for _testShutdown to finish: on OS X, when the server |
---|
1890 | n/a | # closes the connection the client also becomes disconnected, |
---|
1891 | n/a | # and the client's shutdown call will fail. (Issue #4397.) |
---|
1892 | n/a | self.done.wait() |
---|
1893 | n/a | |
---|
1894 | n/a | def _testShutdown(self): |
---|
1895 | n/a | self.serv_conn.send(MSG) |
---|
1896 | n/a | self.serv_conn.shutdown(2) |
---|
1897 | n/a | |
---|
1898 | n/a | testShutdown_overflow = support.cpython_only(testShutdown) |
---|
1899 | n/a | |
---|
1900 | n/a | @support.cpython_only |
---|
1901 | n/a | def _testShutdown_overflow(self): |
---|
1902 | n/a | import _testcapi |
---|
1903 | n/a | self.serv_conn.send(MSG) |
---|
1904 | n/a | # Issue 15989 |
---|
1905 | n/a | self.assertRaises(OverflowError, self.serv_conn.shutdown, |
---|
1906 | n/a | _testcapi.INT_MAX + 1) |
---|
1907 | n/a | self.assertRaises(OverflowError, self.serv_conn.shutdown, |
---|
1908 | n/a | 2 + (_testcapi.UINT_MAX + 1)) |
---|
1909 | n/a | self.serv_conn.shutdown(2) |
---|
1910 | n/a | |
---|
1911 | n/a | def testDetach(self): |
---|
1912 | n/a | # Testing detach() |
---|
1913 | n/a | fileno = self.cli_conn.fileno() |
---|
1914 | n/a | f = self.cli_conn.detach() |
---|
1915 | n/a | self.assertEqual(f, fileno) |
---|
1916 | n/a | # cli_conn cannot be used anymore... |
---|
1917 | n/a | self.assertTrue(self.cli_conn._closed) |
---|
1918 | n/a | self.assertRaises(OSError, self.cli_conn.recv, 1024) |
---|
1919 | n/a | self.cli_conn.close() |
---|
1920 | n/a | # ...but we can create another socket using the (still open) |
---|
1921 | n/a | # file descriptor |
---|
1922 | n/a | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, fileno=f) |
---|
1923 | n/a | self.addCleanup(sock.close) |
---|
1924 | n/a | msg = sock.recv(1024) |
---|
1925 | n/a | self.assertEqual(msg, MSG) |
---|
1926 | n/a | |
---|
1927 | n/a | def _testDetach(self): |
---|
1928 | n/a | self.serv_conn.send(MSG) |
---|
1929 | n/a | |
---|
1930 | n/a | @unittest.skipUnless(thread, 'Threading required for this test.') |
---|
1931 | n/a | class BasicUDPTest(ThreadedUDPSocketTest): |
---|
1932 | n/a | |
---|
1933 | n/a | def __init__(self, methodName='runTest'): |
---|
1934 | n/a | ThreadedUDPSocketTest.__init__(self, methodName=methodName) |
---|
1935 | n/a | |
---|
1936 | n/a | def testSendtoAndRecv(self): |
---|
1937 | n/a | # Testing sendto() and Recv() over UDP |
---|
1938 | n/a | msg = self.serv.recv(len(MSG)) |
---|
1939 | n/a | self.assertEqual(msg, MSG) |
---|
1940 | n/a | |
---|
1941 | n/a | def _testSendtoAndRecv(self): |
---|
1942 | n/a | self.cli.sendto(MSG, 0, (HOST, self.port)) |
---|
1943 | n/a | |
---|
1944 | n/a | def testRecvFrom(self): |
---|
1945 | n/a | # Testing recvfrom() over UDP |
---|
1946 | n/a | msg, addr = self.serv.recvfrom(len(MSG)) |
---|
1947 | n/a | self.assertEqual(msg, MSG) |
---|
1948 | n/a | |
---|
1949 | n/a | def _testRecvFrom(self): |
---|
1950 | n/a | self.cli.sendto(MSG, 0, (HOST, self.port)) |
---|
1951 | n/a | |
---|
1952 | n/a | def testRecvFromNegative(self): |
---|
1953 | n/a | # Negative lengths passed to recvfrom should give ValueError. |
---|
1954 | n/a | self.assertRaises(ValueError, self.serv.recvfrom, -1) |
---|
1955 | n/a | |
---|
1956 | n/a | def _testRecvFromNegative(self): |
---|
1957 | n/a | self.cli.sendto(MSG, 0, (HOST, self.port)) |
---|
1958 | n/a | |
---|
1959 | n/a | # Tests for the sendmsg()/recvmsg() interface. Where possible, the |
---|
1960 | n/a | # same test code is used with different families and types of socket |
---|
1961 | n/a | # (e.g. stream, datagram), and tests using recvmsg() are repeated |
---|
1962 | n/a | # using recvmsg_into(). |
---|
1963 | n/a | # |
---|
1964 | n/a | # The generic test classes such as SendmsgTests and |
---|
1965 | n/a | # RecvmsgGenericTests inherit from SendrecvmsgBase and expect to be |
---|
1966 | n/a | # supplied with sockets cli_sock and serv_sock representing the |
---|
1967 | n/a | # client's and the server's end of the connection respectively, and |
---|
1968 | n/a | # attributes cli_addr and serv_addr holding their (numeric where |
---|
1969 | n/a | # appropriate) addresses. |
---|
1970 | n/a | # |
---|
1971 | n/a | # The final concrete test classes combine these with subclasses of |
---|
1972 | n/a | # SocketTestBase which set up client and server sockets of a specific |
---|
1973 | n/a | # type, and with subclasses of SendrecvmsgBase such as |
---|
1974 | n/a | # SendrecvmsgDgramBase and SendrecvmsgConnectedBase which map these |
---|
1975 | n/a | # sockets to cli_sock and serv_sock and override the methods and |
---|
1976 | n/a | # attributes of SendrecvmsgBase to fill in destination addresses if |
---|
1977 | n/a | # needed when sending, check for specific flags in msg_flags, etc. |
---|
1978 | n/a | # |
---|
1979 | n/a | # RecvmsgIntoMixin provides a version of doRecvmsg() implemented using |
---|
1980 | n/a | # recvmsg_into(). |
---|
1981 | n/a | |
---|
1982 | n/a | # XXX: like the other datagram (UDP) tests in this module, the code |
---|
1983 | n/a | # here assumes that datagram delivery on the local machine will be |
---|
1984 | n/a | # reliable. |
---|
1985 | n/a | |
---|
1986 | n/a | class SendrecvmsgBase(ThreadSafeCleanupTestCase): |
---|
1987 | n/a | # Base class for sendmsg()/recvmsg() tests. |
---|
1988 | n/a | |
---|
1989 | n/a | # Time in seconds to wait before considering a test failed, or |
---|
1990 | n/a | # None for no timeout. Not all tests actually set a timeout. |
---|
1991 | n/a | fail_timeout = 3.0 |
---|
1992 | n/a | |
---|
1993 | n/a | def setUp(self): |
---|
1994 | n/a | self.misc_event = threading.Event() |
---|
1995 | n/a | super().setUp() |
---|
1996 | n/a | |
---|
1997 | n/a | def sendToServer(self, msg): |
---|
1998 | n/a | # Send msg to the server. |
---|
1999 | n/a | return self.cli_sock.send(msg) |
---|
2000 | n/a | |
---|
2001 | n/a | # Tuple of alternative default arguments for sendmsg() when called |
---|
2002 | n/a | # via sendmsgToServer() (e.g. to include a destination address). |
---|
2003 | n/a | sendmsg_to_server_defaults = () |
---|
2004 | n/a | |
---|
2005 | n/a | def sendmsgToServer(self, *args): |
---|
2006 | n/a | # Call sendmsg() on self.cli_sock with the given arguments, |
---|
2007 | n/a | # filling in any arguments which are not supplied with the |
---|
2008 | n/a | # corresponding items of self.sendmsg_to_server_defaults, if |
---|
2009 | n/a | # any. |
---|
2010 | n/a | return self.cli_sock.sendmsg( |
---|
2011 | n/a | *(args + self.sendmsg_to_server_defaults[len(args):])) |
---|
2012 | n/a | |
---|
2013 | n/a | def doRecvmsg(self, sock, bufsize, *args): |
---|
2014 | n/a | # Call recvmsg() on sock with given arguments and return its |
---|
2015 | n/a | # result. Should be used for tests which can use either |
---|
2016 | n/a | # recvmsg() or recvmsg_into() - RecvmsgIntoMixin overrides |
---|
2017 | n/a | # this method with one which emulates it using recvmsg_into(), |
---|
2018 | n/a | # thus allowing the same test to be used for both methods. |
---|
2019 | n/a | result = sock.recvmsg(bufsize, *args) |
---|
2020 | n/a | self.registerRecvmsgResult(result) |
---|
2021 | n/a | return result |
---|
2022 | n/a | |
---|
2023 | n/a | def registerRecvmsgResult(self, result): |
---|
2024 | n/a | # Called by doRecvmsg() with the return value of recvmsg() or |
---|
2025 | n/a | # recvmsg_into(). Can be overridden to arrange cleanup based |
---|
2026 | n/a | # on the returned ancillary data, for instance. |
---|
2027 | n/a | pass |
---|
2028 | n/a | |
---|
2029 | n/a | def checkRecvmsgAddress(self, addr1, addr2): |
---|
2030 | n/a | # Called to compare the received address with the address of |
---|
2031 | n/a | # the peer. |
---|
2032 | n/a | self.assertEqual(addr1, addr2) |
---|
2033 | n/a | |
---|
2034 | n/a | # Flags that are normally unset in msg_flags |
---|
2035 | n/a | msg_flags_common_unset = 0 |
---|
2036 | n/a | for name in ("MSG_CTRUNC", "MSG_OOB"): |
---|
2037 | n/a | msg_flags_common_unset |= getattr(socket, name, 0) |
---|
2038 | n/a | |
---|
2039 | n/a | # Flags that are normally set |
---|
2040 | n/a | msg_flags_common_set = 0 |
---|
2041 | n/a | |
---|
2042 | n/a | # Flags set when a complete record has been received (e.g. MSG_EOR |
---|
2043 | n/a | # for SCTP) |
---|
2044 | n/a | msg_flags_eor_indicator = 0 |
---|
2045 | n/a | |
---|
2046 | n/a | # Flags set when a complete record has not been received |
---|
2047 | n/a | # (e.g. MSG_TRUNC for datagram sockets) |
---|
2048 | n/a | msg_flags_non_eor_indicator = 0 |
---|
2049 | n/a | |
---|
2050 | n/a | def checkFlags(self, flags, eor=None, checkset=0, checkunset=0, ignore=0): |
---|
2051 | n/a | # Method to check the value of msg_flags returned by recvmsg[_into](). |
---|
2052 | n/a | # |
---|
2053 | n/a | # Checks that all bits in msg_flags_common_set attribute are |
---|
2054 | n/a | # set in "flags" and all bits in msg_flags_common_unset are |
---|
2055 | n/a | # unset. |
---|
2056 | n/a | # |
---|
2057 | n/a | # The "eor" argument specifies whether the flags should |
---|
2058 | n/a | # indicate that a full record (or datagram) has been received. |
---|
2059 | n/a | # If "eor" is None, no checks are done; otherwise, checks |
---|
2060 | n/a | # that: |
---|
2061 | n/a | # |
---|
2062 | n/a | # * if "eor" is true, all bits in msg_flags_eor_indicator are |
---|
2063 | n/a | # set and all bits in msg_flags_non_eor_indicator are unset |
---|
2064 | n/a | # |
---|
2065 | n/a | # * if "eor" is false, all bits in msg_flags_non_eor_indicator |
---|
2066 | n/a | # are set and all bits in msg_flags_eor_indicator are unset |
---|
2067 | n/a | # |
---|
2068 | n/a | # If "checkset" and/or "checkunset" are supplied, they require |
---|
2069 | n/a | # the given bits to be set or unset respectively, overriding |
---|
2070 | n/a | # what the attributes require for those bits. |
---|
2071 | n/a | # |
---|
2072 | n/a | # If any bits are set in "ignore", they will not be checked, |
---|
2073 | n/a | # regardless of the other inputs. |
---|
2074 | n/a | # |
---|
2075 | n/a | # Will raise Exception if the inputs require a bit to be both |
---|
2076 | n/a | # set and unset, and it is not ignored. |
---|
2077 | n/a | |
---|
2078 | n/a | defaultset = self.msg_flags_common_set |
---|
2079 | n/a | defaultunset = self.msg_flags_common_unset |
---|
2080 | n/a | |
---|
2081 | n/a | if eor: |
---|
2082 | n/a | defaultset |= self.msg_flags_eor_indicator |
---|
2083 | n/a | defaultunset |= self.msg_flags_non_eor_indicator |
---|
2084 | n/a | elif eor is not None: |
---|
2085 | n/a | defaultset |= self.msg_flags_non_eor_indicator |
---|
2086 | n/a | defaultunset |= self.msg_flags_eor_indicator |
---|
2087 | n/a | |
---|
2088 | n/a | # Function arguments override defaults |
---|
2089 | n/a | defaultset &= ~checkunset |
---|
2090 | n/a | defaultunset &= ~checkset |
---|
2091 | n/a | |
---|
2092 | n/a | # Merge arguments with remaining defaults, and check for conflicts |
---|
2093 | n/a | checkset |= defaultset |
---|
2094 | n/a | checkunset |= defaultunset |
---|
2095 | n/a | inboth = checkset & checkunset & ~ignore |
---|
2096 | n/a | if inboth: |
---|
2097 | n/a | raise Exception("contradictory set, unset requirements for flags " |
---|
2098 | n/a | "{0:#x}".format(inboth)) |
---|
2099 | n/a | |
---|
2100 | n/a | # Compare with given msg_flags value |
---|
2101 | n/a | mask = (checkset | checkunset) & ~ignore |
---|
2102 | n/a | self.assertEqual(flags & mask, checkset & mask) |
---|
2103 | n/a | |
---|
2104 | n/a | |
---|
2105 | n/a | class RecvmsgIntoMixin(SendrecvmsgBase): |
---|
2106 | n/a | # Mixin to implement doRecvmsg() using recvmsg_into(). |
---|
2107 | n/a | |
---|
2108 | n/a | def doRecvmsg(self, sock, bufsize, *args): |
---|
2109 | n/a | buf = bytearray(bufsize) |
---|
2110 | n/a | result = sock.recvmsg_into([buf], *args) |
---|
2111 | n/a | self.registerRecvmsgResult(result) |
---|
2112 | n/a | self.assertGreaterEqual(result[0], 0) |
---|
2113 | n/a | self.assertLessEqual(result[0], bufsize) |
---|
2114 | n/a | return (bytes(buf[:result[0]]),) + result[1:] |
---|
2115 | n/a | |
---|
2116 | n/a | |
---|
2117 | n/a | class SendrecvmsgDgramFlagsBase(SendrecvmsgBase): |
---|
2118 | n/a | # Defines flags to be checked in msg_flags for datagram sockets. |
---|
2119 | n/a | |
---|
2120 | n/a | @property |
---|
2121 | n/a | def msg_flags_non_eor_indicator(self): |
---|
2122 | n/a | return super().msg_flags_non_eor_indicator | socket.MSG_TRUNC |
---|
2123 | n/a | |
---|
2124 | n/a | |
---|
2125 | n/a | class SendrecvmsgSCTPFlagsBase(SendrecvmsgBase): |
---|
2126 | n/a | # Defines flags to be checked in msg_flags for SCTP sockets. |
---|
2127 | n/a | |
---|
2128 | n/a | @property |
---|
2129 | n/a | def msg_flags_eor_indicator(self): |
---|
2130 | n/a | return super().msg_flags_eor_indicator | socket.MSG_EOR |
---|
2131 | n/a | |
---|
2132 | n/a | |
---|
2133 | n/a | class SendrecvmsgConnectionlessBase(SendrecvmsgBase): |
---|
2134 | n/a | # Base class for tests on connectionless-mode sockets. Users must |
---|
2135 | n/a | # supply sockets on attributes cli and serv to be mapped to |
---|
2136 | n/a | # cli_sock and serv_sock respectively. |
---|
2137 | n/a | |
---|
2138 | n/a | @property |
---|
2139 | n/a | def serv_sock(self): |
---|
2140 | n/a | return self.serv |
---|
2141 | n/a | |
---|
2142 | n/a | @property |
---|
2143 | n/a | def cli_sock(self): |
---|
2144 | n/a | return self.cli |
---|
2145 | n/a | |
---|
2146 | n/a | @property |
---|
2147 | n/a | def sendmsg_to_server_defaults(self): |
---|
2148 | n/a | return ([], [], 0, self.serv_addr) |
---|
2149 | n/a | |
---|
2150 | n/a | def sendToServer(self, msg): |
---|
2151 | n/a | return self.cli_sock.sendto(msg, self.serv_addr) |
---|
2152 | n/a | |
---|
2153 | n/a | |
---|
2154 | n/a | class SendrecvmsgConnectedBase(SendrecvmsgBase): |
---|
2155 | n/a | # Base class for tests on connected sockets. Users must supply |
---|
2156 | n/a | # sockets on attributes serv_conn and cli_conn (representing the |
---|
2157 | n/a | # connections *to* the server and the client), to be mapped to |
---|
2158 | n/a | # cli_sock and serv_sock respectively. |
---|
2159 | n/a | |
---|
2160 | n/a | @property |
---|
2161 | n/a | def serv_sock(self): |
---|
2162 | n/a | return self.cli_conn |
---|
2163 | n/a | |
---|
2164 | n/a | @property |
---|
2165 | n/a | def cli_sock(self): |
---|
2166 | n/a | return self.serv_conn |
---|
2167 | n/a | |
---|
2168 | n/a | def checkRecvmsgAddress(self, addr1, addr2): |
---|
2169 | n/a | # Address is currently "unspecified" for a connected socket, |
---|
2170 | n/a | # so we don't examine it |
---|
2171 | n/a | pass |
---|
2172 | n/a | |
---|
2173 | n/a | |
---|
2174 | n/a | class SendrecvmsgServerTimeoutBase(SendrecvmsgBase): |
---|
2175 | n/a | # Base class to set a timeout on server's socket. |
---|
2176 | n/a | |
---|
2177 | n/a | def setUp(self): |
---|
2178 | n/a | super().setUp() |
---|
2179 | n/a | self.serv_sock.settimeout(self.fail_timeout) |
---|
2180 | n/a | |
---|
2181 | n/a | |
---|
2182 | n/a | class SendmsgTests(SendrecvmsgServerTimeoutBase): |
---|
2183 | n/a | # Tests for sendmsg() which can use any socket type and do not |
---|
2184 | n/a | # involve recvmsg() or recvmsg_into(). |
---|
2185 | n/a | |
---|
2186 | n/a | def testSendmsg(self): |
---|
2187 | n/a | # Send a simple message with sendmsg(). |
---|
2188 | n/a | self.assertEqual(self.serv_sock.recv(len(MSG)), MSG) |
---|
2189 | n/a | |
---|
2190 | n/a | def _testSendmsg(self): |
---|
2191 | n/a | self.assertEqual(self.sendmsgToServer([MSG]), len(MSG)) |
---|
2192 | n/a | |
---|
2193 | n/a | def testSendmsgDataGenerator(self): |
---|
2194 | n/a | # Send from buffer obtained from a generator (not a sequence). |
---|
2195 | n/a | self.assertEqual(self.serv_sock.recv(len(MSG)), MSG) |
---|
2196 | n/a | |
---|
2197 | n/a | def _testSendmsgDataGenerator(self): |
---|
2198 | n/a | self.assertEqual(self.sendmsgToServer((o for o in [MSG])), |
---|
2199 | n/a | len(MSG)) |
---|
2200 | n/a | |
---|
2201 | n/a | def testSendmsgAncillaryGenerator(self): |
---|
2202 | n/a | # Gather (empty) ancillary data from a generator. |
---|
2203 | n/a | self.assertEqual(self.serv_sock.recv(len(MSG)), MSG) |
---|
2204 | n/a | |
---|
2205 | n/a | def _testSendmsgAncillaryGenerator(self): |
---|
2206 | n/a | self.assertEqual(self.sendmsgToServer([MSG], (o for o in [])), |
---|
2207 | n/a | len(MSG)) |
---|
2208 | n/a | |
---|
2209 | n/a | def testSendmsgArray(self): |
---|
2210 | n/a | # Send data from an array instead of the usual bytes object. |
---|
2211 | n/a | self.assertEqual(self.serv_sock.recv(len(MSG)), MSG) |
---|
2212 | n/a | |
---|
2213 | n/a | def _testSendmsgArray(self): |
---|
2214 | n/a | self.assertEqual(self.sendmsgToServer([array.array("B", MSG)]), |
---|
2215 | n/a | len(MSG)) |
---|
2216 | n/a | |
---|
2217 | n/a | def testSendmsgGather(self): |
---|
2218 | n/a | # Send message data from more than one buffer (gather write). |
---|
2219 | n/a | self.assertEqual(self.serv_sock.recv(len(MSG)), MSG) |
---|
2220 | n/a | |
---|
2221 | n/a | def _testSendmsgGather(self): |
---|
2222 | n/a | self.assertEqual(self.sendmsgToServer([MSG[:3], MSG[3:]]), len(MSG)) |
---|
2223 | n/a | |
---|
2224 | n/a | def testSendmsgBadArgs(self): |
---|
2225 | n/a | # Check that sendmsg() rejects invalid arguments. |
---|
2226 | n/a | self.assertEqual(self.serv_sock.recv(1000), b"done") |
---|
2227 | n/a | |
---|
2228 | n/a | def _testSendmsgBadArgs(self): |
---|
2229 | n/a | self.assertRaises(TypeError, self.cli_sock.sendmsg) |
---|
2230 | n/a | self.assertRaises(TypeError, self.sendmsgToServer, |
---|
2231 | n/a | b"not in an iterable") |
---|
2232 | n/a | self.assertRaises(TypeError, self.sendmsgToServer, |
---|
2233 | n/a | object()) |
---|
2234 | n/a | self.assertRaises(TypeError, self.sendmsgToServer, |
---|
2235 | n/a | [object()]) |
---|
2236 | n/a | self.assertRaises(TypeError, self.sendmsgToServer, |
---|
2237 | n/a | [MSG, object()]) |
---|
2238 | n/a | self.assertRaises(TypeError, self.sendmsgToServer, |
---|
2239 | n/a | [MSG], object()) |
---|
2240 | n/a | self.assertRaises(TypeError, self.sendmsgToServer, |
---|
2241 | n/a | [MSG], [], object()) |
---|
2242 | n/a | self.assertRaises(TypeError, self.sendmsgToServer, |
---|
2243 | n/a | [MSG], [], 0, object()) |
---|
2244 | n/a | self.sendToServer(b"done") |
---|
2245 | n/a | |
---|
2246 | n/a | def testSendmsgBadCmsg(self): |
---|
2247 | n/a | # Check that invalid ancillary data items are rejected. |
---|
2248 | n/a | self.assertEqual(self.serv_sock.recv(1000), b"done") |
---|
2249 | n/a | |
---|
2250 | n/a | def _testSendmsgBadCmsg(self): |
---|
2251 | n/a | self.assertRaises(TypeError, self.sendmsgToServer, |
---|
2252 | n/a | [MSG], [object()]) |
---|
2253 | n/a | self.assertRaises(TypeError, self.sendmsgToServer, |
---|
2254 | n/a | [MSG], [(object(), 0, b"data")]) |
---|
2255 | n/a | self.assertRaises(TypeError, self.sendmsgToServer, |
---|
2256 | n/a | [MSG], [(0, object(), b"data")]) |
---|
2257 | n/a | self.assertRaises(TypeError, self.sendmsgToServer, |
---|
2258 | n/a | [MSG], [(0, 0, object())]) |
---|
2259 | n/a | self.assertRaises(TypeError, self.sendmsgToServer, |
---|
2260 | n/a | [MSG], [(0, 0)]) |
---|
2261 | n/a | self.assertRaises(TypeError, self.sendmsgToServer, |
---|
2262 | n/a | [MSG], [(0, 0, b"data", 42)]) |
---|
2263 | n/a | self.sendToServer(b"done") |
---|
2264 | n/a | |
---|
2265 | n/a | @requireAttrs(socket, "CMSG_SPACE") |
---|
2266 | n/a | def testSendmsgBadMultiCmsg(self): |
---|
2267 | n/a | # Check that invalid ancillary data items are rejected when |
---|
2268 | n/a | # more than one item is present. |
---|
2269 | n/a | self.assertEqual(self.serv_sock.recv(1000), b"done") |
---|
2270 | n/a | |
---|
2271 | n/a | @testSendmsgBadMultiCmsg.client_skip |
---|
2272 | n/a | def _testSendmsgBadMultiCmsg(self): |
---|
2273 | n/a | self.assertRaises(TypeError, self.sendmsgToServer, |
---|
2274 | n/a | [MSG], [0, 0, b""]) |
---|
2275 | n/a | self.assertRaises(TypeError, self.sendmsgToServer, |
---|
2276 | n/a | [MSG], [(0, 0, b""), object()]) |
---|
2277 | n/a | self.sendToServer(b"done") |
---|
2278 | n/a | |
---|
2279 | n/a | def testSendmsgExcessCmsgReject(self): |
---|
2280 | n/a | # Check that sendmsg() rejects excess ancillary data items |
---|
2281 | n/a | # when the number that can be sent is limited. |
---|
2282 | n/a | self.assertEqual(self.serv_sock.recv(1000), b"done") |
---|
2283 | n/a | |
---|
2284 | n/a | def _testSendmsgExcessCmsgReject(self): |
---|
2285 | n/a | if not hasattr(socket, "CMSG_SPACE"): |
---|
2286 | n/a | # Can only send one item |
---|
2287 | n/a | with self.assertRaises(OSError) as cm: |
---|
2288 | n/a | self.sendmsgToServer([MSG], [(0, 0, b""), (0, 0, b"")]) |
---|
2289 | n/a | self.assertIsNone(cm.exception.errno) |
---|
2290 | n/a | self.sendToServer(b"done") |
---|
2291 | n/a | |
---|
2292 | n/a | def testSendmsgAfterClose(self): |
---|
2293 | n/a | # Check that sendmsg() fails on a closed socket. |
---|
2294 | n/a | pass |
---|
2295 | n/a | |
---|
2296 | n/a | def _testSendmsgAfterClose(self): |
---|
2297 | n/a | self.cli_sock.close() |
---|
2298 | n/a | self.assertRaises(OSError, self.sendmsgToServer, [MSG]) |
---|
2299 | n/a | |
---|
2300 | n/a | |
---|
2301 | n/a | class SendmsgStreamTests(SendmsgTests): |
---|
2302 | n/a | # Tests for sendmsg() which require a stream socket and do not |
---|
2303 | n/a | # involve recvmsg() or recvmsg_into(). |
---|
2304 | n/a | |
---|
2305 | n/a | def testSendmsgExplicitNoneAddr(self): |
---|
2306 | n/a | # Check that peer address can be specified as None. |
---|
2307 | n/a | self.assertEqual(self.serv_sock.recv(len(MSG)), MSG) |
---|
2308 | n/a | |
---|
2309 | n/a | def _testSendmsgExplicitNoneAddr(self): |
---|
2310 | n/a | self.assertEqual(self.sendmsgToServer([MSG], [], 0, None), len(MSG)) |
---|
2311 | n/a | |
---|
2312 | n/a | def testSendmsgTimeout(self): |
---|
2313 | n/a | # Check that timeout works with sendmsg(). |
---|
2314 | n/a | self.assertEqual(self.serv_sock.recv(512), b"a"*512) |
---|
2315 | n/a | self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
---|
2316 | n/a | |
---|
2317 | n/a | def _testSendmsgTimeout(self): |
---|
2318 | n/a | try: |
---|
2319 | n/a | self.cli_sock.settimeout(0.03) |
---|
2320 | n/a | with self.assertRaises(socket.timeout): |
---|
2321 | n/a | while True: |
---|
2322 | n/a | self.sendmsgToServer([b"a"*512]) |
---|
2323 | n/a | finally: |
---|
2324 | n/a | self.misc_event.set() |
---|
2325 | n/a | |
---|
2326 | n/a | # XXX: would be nice to have more tests for sendmsg flags argument. |
---|
2327 | n/a | |
---|
2328 | n/a | # Linux supports MSG_DONTWAIT when sending, but in general, it |
---|
2329 | n/a | # only works when receiving. Could add other platforms if they |
---|
2330 | n/a | # support it too. |
---|
2331 | n/a | @skipWithClientIf(sys.platform not in {"linux"}, |
---|
2332 | n/a | "MSG_DONTWAIT not known to work on this platform when " |
---|
2333 | n/a | "sending") |
---|
2334 | n/a | def testSendmsgDontWait(self): |
---|
2335 | n/a | # Check that MSG_DONTWAIT in flags causes non-blocking behaviour. |
---|
2336 | n/a | self.assertEqual(self.serv_sock.recv(512), b"a"*512) |
---|
2337 | n/a | self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
---|
2338 | n/a | |
---|
2339 | n/a | @testSendmsgDontWait.client_skip |
---|
2340 | n/a | def _testSendmsgDontWait(self): |
---|
2341 | n/a | try: |
---|
2342 | n/a | with self.assertRaises(OSError) as cm: |
---|
2343 | n/a | while True: |
---|
2344 | n/a | self.sendmsgToServer([b"a"*512], [], socket.MSG_DONTWAIT) |
---|
2345 | n/a | self.assertIn(cm.exception.errno, |
---|
2346 | n/a | (errno.EAGAIN, errno.EWOULDBLOCK)) |
---|
2347 | n/a | finally: |
---|
2348 | n/a | self.misc_event.set() |
---|
2349 | n/a | |
---|
2350 | n/a | |
---|
2351 | n/a | class SendmsgConnectionlessTests(SendmsgTests): |
---|
2352 | n/a | # Tests for sendmsg() which require a connectionless-mode |
---|
2353 | n/a | # (e.g. datagram) socket, and do not involve recvmsg() or |
---|
2354 | n/a | # recvmsg_into(). |
---|
2355 | n/a | |
---|
2356 | n/a | def testSendmsgNoDestAddr(self): |
---|
2357 | n/a | # Check that sendmsg() fails when no destination address is |
---|
2358 | n/a | # given for unconnected socket. |
---|
2359 | n/a | pass |
---|
2360 | n/a | |
---|
2361 | n/a | def _testSendmsgNoDestAddr(self): |
---|
2362 | n/a | self.assertRaises(OSError, self.cli_sock.sendmsg, |
---|
2363 | n/a | [MSG]) |
---|
2364 | n/a | self.assertRaises(OSError, self.cli_sock.sendmsg, |
---|
2365 | n/a | [MSG], [], 0, None) |
---|
2366 | n/a | |
---|
2367 | n/a | |
---|
2368 | n/a | class RecvmsgGenericTests(SendrecvmsgBase): |
---|
2369 | n/a | # Tests for recvmsg() which can also be emulated using |
---|
2370 | n/a | # recvmsg_into(), and can use any socket type. |
---|
2371 | n/a | |
---|
2372 | n/a | def testRecvmsg(self): |
---|
2373 | n/a | # Receive a simple message with recvmsg[_into](). |
---|
2374 | n/a | msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, len(MSG)) |
---|
2375 | n/a | self.assertEqual(msg, MSG) |
---|
2376 | n/a | self.checkRecvmsgAddress(addr, self.cli_addr) |
---|
2377 | n/a | self.assertEqual(ancdata, []) |
---|
2378 | n/a | self.checkFlags(flags, eor=True) |
---|
2379 | n/a | |
---|
2380 | n/a | def _testRecvmsg(self): |
---|
2381 | n/a | self.sendToServer(MSG) |
---|
2382 | n/a | |
---|
2383 | n/a | def testRecvmsgExplicitDefaults(self): |
---|
2384 | n/a | # Test recvmsg[_into]() with default arguments provided explicitly. |
---|
2385 | n/a | msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, |
---|
2386 | n/a | len(MSG), 0, 0) |
---|
2387 | n/a | self.assertEqual(msg, MSG) |
---|
2388 | n/a | self.checkRecvmsgAddress(addr, self.cli_addr) |
---|
2389 | n/a | self.assertEqual(ancdata, []) |
---|
2390 | n/a | self.checkFlags(flags, eor=True) |
---|
2391 | n/a | |
---|
2392 | n/a | def _testRecvmsgExplicitDefaults(self): |
---|
2393 | n/a | self.sendToServer(MSG) |
---|
2394 | n/a | |
---|
2395 | n/a | def testRecvmsgShorter(self): |
---|
2396 | n/a | # Receive a message smaller than buffer. |
---|
2397 | n/a | msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, |
---|
2398 | n/a | len(MSG) + 42) |
---|
2399 | n/a | self.assertEqual(msg, MSG) |
---|
2400 | n/a | self.checkRecvmsgAddress(addr, self.cli_addr) |
---|
2401 | n/a | self.assertEqual(ancdata, []) |
---|
2402 | n/a | self.checkFlags(flags, eor=True) |
---|
2403 | n/a | |
---|
2404 | n/a | def _testRecvmsgShorter(self): |
---|
2405 | n/a | self.sendToServer(MSG) |
---|
2406 | n/a | |
---|
2407 | n/a | # FreeBSD < 8 doesn't always set the MSG_TRUNC flag when a truncated |
---|
2408 | n/a | # datagram is received (issue #13001). |
---|
2409 | n/a | @support.requires_freebsd_version(8) |
---|
2410 | n/a | def testRecvmsgTrunc(self): |
---|
2411 | n/a | # Receive part of message, check for truncation indicators. |
---|
2412 | n/a | msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, |
---|
2413 | n/a | len(MSG) - 3) |
---|
2414 | n/a | self.assertEqual(msg, MSG[:-3]) |
---|
2415 | n/a | self.checkRecvmsgAddress(addr, self.cli_addr) |
---|
2416 | n/a | self.assertEqual(ancdata, []) |
---|
2417 | n/a | self.checkFlags(flags, eor=False) |
---|
2418 | n/a | |
---|
2419 | n/a | @support.requires_freebsd_version(8) |
---|
2420 | n/a | def _testRecvmsgTrunc(self): |
---|
2421 | n/a | self.sendToServer(MSG) |
---|
2422 | n/a | |
---|
2423 | n/a | def testRecvmsgShortAncillaryBuf(self): |
---|
2424 | n/a | # Test ancillary data buffer too small to hold any ancillary data. |
---|
2425 | n/a | msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, |
---|
2426 | n/a | len(MSG), 1) |
---|
2427 | n/a | self.assertEqual(msg, MSG) |
---|
2428 | n/a | self.checkRecvmsgAddress(addr, self.cli_addr) |
---|
2429 | n/a | self.assertEqual(ancdata, []) |
---|
2430 | n/a | self.checkFlags(flags, eor=True) |
---|
2431 | n/a | |
---|
2432 | n/a | def _testRecvmsgShortAncillaryBuf(self): |
---|
2433 | n/a | self.sendToServer(MSG) |
---|
2434 | n/a | |
---|
2435 | n/a | def testRecvmsgLongAncillaryBuf(self): |
---|
2436 | n/a | # Test large ancillary data buffer. |
---|
2437 | n/a | msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, |
---|
2438 | n/a | len(MSG), 10240) |
---|
2439 | n/a | self.assertEqual(msg, MSG) |
---|
2440 | n/a | self.checkRecvmsgAddress(addr, self.cli_addr) |
---|
2441 | n/a | self.assertEqual(ancdata, []) |
---|
2442 | n/a | self.checkFlags(flags, eor=True) |
---|
2443 | n/a | |
---|
2444 | n/a | def _testRecvmsgLongAncillaryBuf(self): |
---|
2445 | n/a | self.sendToServer(MSG) |
---|
2446 | n/a | |
---|
2447 | n/a | def testRecvmsgAfterClose(self): |
---|
2448 | n/a | # Check that recvmsg[_into]() fails on a closed socket. |
---|
2449 | n/a | self.serv_sock.close() |
---|
2450 | n/a | self.assertRaises(OSError, self.doRecvmsg, self.serv_sock, 1024) |
---|
2451 | n/a | |
---|
2452 | n/a | def _testRecvmsgAfterClose(self): |
---|
2453 | n/a | pass |
---|
2454 | n/a | |
---|
2455 | n/a | def testRecvmsgTimeout(self): |
---|
2456 | n/a | # Check that timeout works. |
---|
2457 | n/a | try: |
---|
2458 | n/a | self.serv_sock.settimeout(0.03) |
---|
2459 | n/a | self.assertRaises(socket.timeout, |
---|
2460 | n/a | self.doRecvmsg, self.serv_sock, len(MSG)) |
---|
2461 | n/a | finally: |
---|
2462 | n/a | self.misc_event.set() |
---|
2463 | n/a | |
---|
2464 | n/a | def _testRecvmsgTimeout(self): |
---|
2465 | n/a | self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
---|
2466 | n/a | |
---|
2467 | n/a | @requireAttrs(socket, "MSG_PEEK") |
---|
2468 | n/a | def testRecvmsgPeek(self): |
---|
2469 | n/a | # Check that MSG_PEEK in flags enables examination of pending |
---|
2470 | n/a | # data without consuming it. |
---|
2471 | n/a | |
---|
2472 | n/a | # Receive part of data with MSG_PEEK. |
---|
2473 | n/a | msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, |
---|
2474 | n/a | len(MSG) - 3, 0, |
---|
2475 | n/a | socket.MSG_PEEK) |
---|
2476 | n/a | self.assertEqual(msg, MSG[:-3]) |
---|
2477 | n/a | self.checkRecvmsgAddress(addr, self.cli_addr) |
---|
2478 | n/a | self.assertEqual(ancdata, []) |
---|
2479 | n/a | # Ignoring MSG_TRUNC here (so this test is the same for stream |
---|
2480 | n/a | # and datagram sockets). Some wording in POSIX seems to |
---|
2481 | n/a | # suggest that it needn't be set when peeking, but that may |
---|
2482 | n/a | # just be a slip. |
---|
2483 | n/a | self.checkFlags(flags, eor=False, |
---|
2484 | n/a | ignore=getattr(socket, "MSG_TRUNC", 0)) |
---|
2485 | n/a | |
---|
2486 | n/a | # Receive all data with MSG_PEEK. |
---|
2487 | n/a | msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, |
---|
2488 | n/a | len(MSG), 0, |
---|
2489 | n/a | socket.MSG_PEEK) |
---|
2490 | n/a | self.assertEqual(msg, MSG) |
---|
2491 | n/a | self.checkRecvmsgAddress(addr, self.cli_addr) |
---|
2492 | n/a | self.assertEqual(ancdata, []) |
---|
2493 | n/a | self.checkFlags(flags, eor=True) |
---|
2494 | n/a | |
---|
2495 | n/a | # Check that the same data can still be received normally. |
---|
2496 | n/a | msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, len(MSG)) |
---|
2497 | n/a | self.assertEqual(msg, MSG) |
---|
2498 | n/a | self.checkRecvmsgAddress(addr, self.cli_addr) |
---|
2499 | n/a | self.assertEqual(ancdata, []) |
---|
2500 | n/a | self.checkFlags(flags, eor=True) |
---|
2501 | n/a | |
---|
2502 | n/a | @testRecvmsgPeek.client_skip |
---|
2503 | n/a | def _testRecvmsgPeek(self): |
---|
2504 | n/a | self.sendToServer(MSG) |
---|
2505 | n/a | |
---|
2506 | n/a | @requireAttrs(socket.socket, "sendmsg") |
---|
2507 | n/a | def testRecvmsgFromSendmsg(self): |
---|
2508 | n/a | # Test receiving with recvmsg[_into]() when message is sent |
---|
2509 | n/a | # using sendmsg(). |
---|
2510 | n/a | self.serv_sock.settimeout(self.fail_timeout) |
---|
2511 | n/a | msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, len(MSG)) |
---|
2512 | n/a | self.assertEqual(msg, MSG) |
---|
2513 | n/a | self.checkRecvmsgAddress(addr, self.cli_addr) |
---|
2514 | n/a | self.assertEqual(ancdata, []) |
---|
2515 | n/a | self.checkFlags(flags, eor=True) |
---|
2516 | n/a | |
---|
2517 | n/a | @testRecvmsgFromSendmsg.client_skip |
---|
2518 | n/a | def _testRecvmsgFromSendmsg(self): |
---|
2519 | n/a | self.assertEqual(self.sendmsgToServer([MSG[:3], MSG[3:]]), len(MSG)) |
---|
2520 | n/a | |
---|
2521 | n/a | |
---|
2522 | n/a | class RecvmsgGenericStreamTests(RecvmsgGenericTests): |
---|
2523 | n/a | # Tests which require a stream socket and can use either recvmsg() |
---|
2524 | n/a | # or recvmsg_into(). |
---|
2525 | n/a | |
---|
2526 | n/a | def testRecvmsgEOF(self): |
---|
2527 | n/a | # Receive end-of-stream indicator (b"", peer socket closed). |
---|
2528 | n/a | msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, 1024) |
---|
2529 | n/a | self.assertEqual(msg, b"") |
---|
2530 | n/a | self.checkRecvmsgAddress(addr, self.cli_addr) |
---|
2531 | n/a | self.assertEqual(ancdata, []) |
---|
2532 | n/a | self.checkFlags(flags, eor=None) # Might not have end-of-record marker |
---|
2533 | n/a | |
---|
2534 | n/a | def _testRecvmsgEOF(self): |
---|
2535 | n/a | self.cli_sock.close() |
---|
2536 | n/a | |
---|
2537 | n/a | def testRecvmsgOverflow(self): |
---|
2538 | n/a | # Receive a message in more than one chunk. |
---|
2539 | n/a | seg1, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, |
---|
2540 | n/a | len(MSG) - 3) |
---|
2541 | n/a | self.checkRecvmsgAddress(addr, self.cli_addr) |
---|
2542 | n/a | self.assertEqual(ancdata, []) |
---|
2543 | n/a | self.checkFlags(flags, eor=False) |
---|
2544 | n/a | |
---|
2545 | n/a | seg2, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, 1024) |
---|
2546 | n/a | self.checkRecvmsgAddress(addr, self.cli_addr) |
---|
2547 | n/a | self.assertEqual(ancdata, []) |
---|
2548 | n/a | self.checkFlags(flags, eor=True) |
---|
2549 | n/a | |
---|
2550 | n/a | msg = seg1 + seg2 |
---|
2551 | n/a | self.assertEqual(msg, MSG) |
---|
2552 | n/a | |
---|
2553 | n/a | def _testRecvmsgOverflow(self): |
---|
2554 | n/a | self.sendToServer(MSG) |
---|
2555 | n/a | |
---|
2556 | n/a | |
---|
2557 | n/a | class RecvmsgTests(RecvmsgGenericTests): |
---|
2558 | n/a | # Tests for recvmsg() which can use any socket type. |
---|
2559 | n/a | |
---|
2560 | n/a | def testRecvmsgBadArgs(self): |
---|
2561 | n/a | # Check that recvmsg() rejects invalid arguments. |
---|
2562 | n/a | self.assertRaises(TypeError, self.serv_sock.recvmsg) |
---|
2563 | n/a | self.assertRaises(ValueError, self.serv_sock.recvmsg, |
---|
2564 | n/a | -1, 0, 0) |
---|
2565 | n/a | self.assertRaises(ValueError, self.serv_sock.recvmsg, |
---|
2566 | n/a | len(MSG), -1, 0) |
---|
2567 | n/a | self.assertRaises(TypeError, self.serv_sock.recvmsg, |
---|
2568 | n/a | [bytearray(10)], 0, 0) |
---|
2569 | n/a | self.assertRaises(TypeError, self.serv_sock.recvmsg, |
---|
2570 | n/a | object(), 0, 0) |
---|
2571 | n/a | self.assertRaises(TypeError, self.serv_sock.recvmsg, |
---|
2572 | n/a | len(MSG), object(), 0) |
---|
2573 | n/a | self.assertRaises(TypeError, self.serv_sock.recvmsg, |
---|
2574 | n/a | len(MSG), 0, object()) |
---|
2575 | n/a | |
---|
2576 | n/a | msg, ancdata, flags, addr = self.serv_sock.recvmsg(len(MSG), 0, 0) |
---|
2577 | n/a | self.assertEqual(msg, MSG) |
---|
2578 | n/a | self.checkRecvmsgAddress(addr, self.cli_addr) |
---|
2579 | n/a | self.assertEqual(ancdata, []) |
---|
2580 | n/a | self.checkFlags(flags, eor=True) |
---|
2581 | n/a | |
---|
2582 | n/a | def _testRecvmsgBadArgs(self): |
---|
2583 | n/a | self.sendToServer(MSG) |
---|
2584 | n/a | |
---|
2585 | n/a | |
---|
2586 | n/a | class RecvmsgIntoTests(RecvmsgIntoMixin, RecvmsgGenericTests): |
---|
2587 | n/a | # Tests for recvmsg_into() which can use any socket type. |
---|
2588 | n/a | |
---|
2589 | n/a | def testRecvmsgIntoBadArgs(self): |
---|
2590 | n/a | # Check that recvmsg_into() rejects invalid arguments. |
---|
2591 | n/a | buf = bytearray(len(MSG)) |
---|
2592 | n/a | self.assertRaises(TypeError, self.serv_sock.recvmsg_into) |
---|
2593 | n/a | self.assertRaises(TypeError, self.serv_sock.recvmsg_into, |
---|
2594 | n/a | len(MSG), 0, 0) |
---|
2595 | n/a | self.assertRaises(TypeError, self.serv_sock.recvmsg_into, |
---|
2596 | n/a | buf, 0, 0) |
---|
2597 | n/a | self.assertRaises(TypeError, self.serv_sock.recvmsg_into, |
---|
2598 | n/a | [object()], 0, 0) |
---|
2599 | n/a | self.assertRaises(TypeError, self.serv_sock.recvmsg_into, |
---|
2600 | n/a | [b"I'm not writable"], 0, 0) |
---|
2601 | n/a | self.assertRaises(TypeError, self.serv_sock.recvmsg_into, |
---|
2602 | n/a | [buf, object()], 0, 0) |
---|
2603 | n/a | self.assertRaises(ValueError, self.serv_sock.recvmsg_into, |
---|
2604 | n/a | [buf], -1, 0) |
---|
2605 | n/a | self.assertRaises(TypeError, self.serv_sock.recvmsg_into, |
---|
2606 | n/a | [buf], object(), 0) |
---|
2607 | n/a | self.assertRaises(TypeError, self.serv_sock.recvmsg_into, |
---|
2608 | n/a | [buf], 0, object()) |
---|
2609 | n/a | |
---|
2610 | n/a | nbytes, ancdata, flags, addr = self.serv_sock.recvmsg_into([buf], 0, 0) |
---|
2611 | n/a | self.assertEqual(nbytes, len(MSG)) |
---|
2612 | n/a | self.assertEqual(buf, bytearray(MSG)) |
---|
2613 | n/a | self.checkRecvmsgAddress(addr, self.cli_addr) |
---|
2614 | n/a | self.assertEqual(ancdata, []) |
---|
2615 | n/a | self.checkFlags(flags, eor=True) |
---|
2616 | n/a | |
---|
2617 | n/a | def _testRecvmsgIntoBadArgs(self): |
---|
2618 | n/a | self.sendToServer(MSG) |
---|
2619 | n/a | |
---|
2620 | n/a | def testRecvmsgIntoGenerator(self): |
---|
2621 | n/a | # Receive into buffer obtained from a generator (not a sequence). |
---|
2622 | n/a | buf = bytearray(len(MSG)) |
---|
2623 | n/a | nbytes, ancdata, flags, addr = self.serv_sock.recvmsg_into( |
---|
2624 | n/a | (o for o in [buf])) |
---|
2625 | n/a | self.assertEqual(nbytes, len(MSG)) |
---|
2626 | n/a | self.assertEqual(buf, bytearray(MSG)) |
---|
2627 | n/a | self.checkRecvmsgAddress(addr, self.cli_addr) |
---|
2628 | n/a | self.assertEqual(ancdata, []) |
---|
2629 | n/a | self.checkFlags(flags, eor=True) |
---|
2630 | n/a | |
---|
2631 | n/a | def _testRecvmsgIntoGenerator(self): |
---|
2632 | n/a | self.sendToServer(MSG) |
---|
2633 | n/a | |
---|
2634 | n/a | def testRecvmsgIntoArray(self): |
---|
2635 | n/a | # Receive into an array rather than the usual bytearray. |
---|
2636 | n/a | buf = array.array("B", [0] * len(MSG)) |
---|
2637 | n/a | nbytes, ancdata, flags, addr = self.serv_sock.recvmsg_into([buf]) |
---|
2638 | n/a | self.assertEqual(nbytes, len(MSG)) |
---|
2639 | n/a | self.assertEqual(buf.tobytes(), MSG) |
---|
2640 | n/a | self.checkRecvmsgAddress(addr, self.cli_addr) |
---|
2641 | n/a | self.assertEqual(ancdata, []) |
---|
2642 | n/a | self.checkFlags(flags, eor=True) |
---|
2643 | n/a | |
---|
2644 | n/a | def _testRecvmsgIntoArray(self): |
---|
2645 | n/a | self.sendToServer(MSG) |
---|
2646 | n/a | |
---|
2647 | n/a | def testRecvmsgIntoScatter(self): |
---|
2648 | n/a | # Receive into multiple buffers (scatter write). |
---|
2649 | n/a | b1 = bytearray(b"----") |
---|
2650 | n/a | b2 = bytearray(b"0123456789") |
---|
2651 | n/a | b3 = bytearray(b"--------------") |
---|
2652 | n/a | nbytes, ancdata, flags, addr = self.serv_sock.recvmsg_into( |
---|
2653 | n/a | [b1, memoryview(b2)[2:9], b3]) |
---|
2654 | n/a | self.assertEqual(nbytes, len(b"Mary had a little lamb")) |
---|
2655 | n/a | self.assertEqual(b1, bytearray(b"Mary")) |
---|
2656 | n/a | self.assertEqual(b2, bytearray(b"01 had a 9")) |
---|
2657 | n/a | self.assertEqual(b3, bytearray(b"little lamb---")) |
---|
2658 | n/a | self.checkRecvmsgAddress(addr, self.cli_addr) |
---|
2659 | n/a | self.assertEqual(ancdata, []) |
---|
2660 | n/a | self.checkFlags(flags, eor=True) |
---|
2661 | n/a | |
---|
2662 | n/a | def _testRecvmsgIntoScatter(self): |
---|
2663 | n/a | self.sendToServer(b"Mary had a little lamb") |
---|
2664 | n/a | |
---|
2665 | n/a | |
---|
2666 | n/a | class CmsgMacroTests(unittest.TestCase): |
---|
2667 | n/a | # Test the functions CMSG_LEN() and CMSG_SPACE(). Tests |
---|
2668 | n/a | # assumptions used by sendmsg() and recvmsg[_into](), which share |
---|
2669 | n/a | # code with these functions. |
---|
2670 | n/a | |
---|
2671 | n/a | # Match the definition in socketmodule.c |
---|
2672 | n/a | try: |
---|
2673 | n/a | import _testcapi |
---|
2674 | n/a | except ImportError: |
---|
2675 | n/a | socklen_t_limit = 0x7fffffff |
---|
2676 | n/a | else: |
---|
2677 | n/a | socklen_t_limit = min(0x7fffffff, _testcapi.INT_MAX) |
---|
2678 | n/a | |
---|
2679 | n/a | @requireAttrs(socket, "CMSG_LEN") |
---|
2680 | n/a | def testCMSG_LEN(self): |
---|
2681 | n/a | # Test CMSG_LEN() with various valid and invalid values, |
---|
2682 | n/a | # checking the assumptions used by recvmsg() and sendmsg(). |
---|
2683 | n/a | toobig = self.socklen_t_limit - socket.CMSG_LEN(0) + 1 |
---|
2684 | n/a | values = list(range(257)) + list(range(toobig - 257, toobig)) |
---|
2685 | n/a | |
---|
2686 | n/a | # struct cmsghdr has at least three members, two of which are ints |
---|
2687 | n/a | self.assertGreater(socket.CMSG_LEN(0), array.array("i").itemsize * 2) |
---|
2688 | n/a | for n in values: |
---|
2689 | n/a | ret = socket.CMSG_LEN(n) |
---|
2690 | n/a | # This is how recvmsg() calculates the data size |
---|
2691 | n/a | self.assertEqual(ret - socket.CMSG_LEN(0), n) |
---|
2692 | n/a | self.assertLessEqual(ret, self.socklen_t_limit) |
---|
2693 | n/a | |
---|
2694 | n/a | self.assertRaises(OverflowError, socket.CMSG_LEN, -1) |
---|
2695 | n/a | # sendmsg() shares code with these functions, and requires |
---|
2696 | n/a | # that it reject values over the limit. |
---|
2697 | n/a | self.assertRaises(OverflowError, socket.CMSG_LEN, toobig) |
---|
2698 | n/a | self.assertRaises(OverflowError, socket.CMSG_LEN, sys.maxsize) |
---|
2699 | n/a | |
---|
2700 | n/a | @requireAttrs(socket, "CMSG_SPACE") |
---|
2701 | n/a | def testCMSG_SPACE(self): |
---|
2702 | n/a | # Test CMSG_SPACE() with various valid and invalid values, |
---|
2703 | n/a | # checking the assumptions used by sendmsg(). |
---|
2704 | n/a | toobig = self.socklen_t_limit - socket.CMSG_SPACE(1) + 1 |
---|
2705 | n/a | values = list(range(257)) + list(range(toobig - 257, toobig)) |
---|
2706 | n/a | |
---|
2707 | n/a | last = socket.CMSG_SPACE(0) |
---|
2708 | n/a | # struct cmsghdr has at least three members, two of which are ints |
---|
2709 | n/a | self.assertGreater(last, array.array("i").itemsize * 2) |
---|
2710 | n/a | for n in values: |
---|
2711 | n/a | ret = socket.CMSG_SPACE(n) |
---|
2712 | n/a | self.assertGreaterEqual(ret, last) |
---|
2713 | n/a | self.assertGreaterEqual(ret, socket.CMSG_LEN(n)) |
---|
2714 | n/a | self.assertGreaterEqual(ret, n + socket.CMSG_LEN(0)) |
---|
2715 | n/a | self.assertLessEqual(ret, self.socklen_t_limit) |
---|
2716 | n/a | last = ret |
---|
2717 | n/a | |
---|
2718 | n/a | self.assertRaises(OverflowError, socket.CMSG_SPACE, -1) |
---|
2719 | n/a | # sendmsg() shares code with these functions, and requires |
---|
2720 | n/a | # that it reject values over the limit. |
---|
2721 | n/a | self.assertRaises(OverflowError, socket.CMSG_SPACE, toobig) |
---|
2722 | n/a | self.assertRaises(OverflowError, socket.CMSG_SPACE, sys.maxsize) |
---|
2723 | n/a | |
---|
2724 | n/a | |
---|
2725 | n/a | class SCMRightsTest(SendrecvmsgServerTimeoutBase): |
---|
2726 | n/a | # Tests for file descriptor passing on Unix-domain sockets. |
---|
2727 | n/a | |
---|
2728 | n/a | # Invalid file descriptor value that's unlikely to evaluate to a |
---|
2729 | n/a | # real FD even if one of its bytes is replaced with a different |
---|
2730 | n/a | # value (which shouldn't actually happen). |
---|
2731 | n/a | badfd = -0x5555 |
---|
2732 | n/a | |
---|
2733 | n/a | def newFDs(self, n): |
---|
2734 | n/a | # Return a list of n file descriptors for newly-created files |
---|
2735 | n/a | # containing their list indices as ASCII numbers. |
---|
2736 | n/a | fds = [] |
---|
2737 | n/a | for i in range(n): |
---|
2738 | n/a | fd, path = tempfile.mkstemp() |
---|
2739 | n/a | self.addCleanup(os.unlink, path) |
---|
2740 | n/a | self.addCleanup(os.close, fd) |
---|
2741 | n/a | os.write(fd, str(i).encode()) |
---|
2742 | n/a | fds.append(fd) |
---|
2743 | n/a | return fds |
---|
2744 | n/a | |
---|
2745 | n/a | def checkFDs(self, fds): |
---|
2746 | n/a | # Check that the file descriptors in the given list contain |
---|
2747 | n/a | # their correct list indices as ASCII numbers. |
---|
2748 | n/a | for n, fd in enumerate(fds): |
---|
2749 | n/a | os.lseek(fd, 0, os.SEEK_SET) |
---|
2750 | n/a | self.assertEqual(os.read(fd, 1024), str(n).encode()) |
---|
2751 | n/a | |
---|
2752 | n/a | def registerRecvmsgResult(self, result): |
---|
2753 | n/a | self.addCleanup(self.closeRecvmsgFDs, result) |
---|
2754 | n/a | |
---|
2755 | n/a | def closeRecvmsgFDs(self, recvmsg_result): |
---|
2756 | n/a | # Close all file descriptors specified in the ancillary data |
---|
2757 | n/a | # of the given return value from recvmsg() or recvmsg_into(). |
---|
2758 | n/a | for cmsg_level, cmsg_type, cmsg_data in recvmsg_result[1]: |
---|
2759 | n/a | if (cmsg_level == socket.SOL_SOCKET and |
---|
2760 | n/a | cmsg_type == socket.SCM_RIGHTS): |
---|
2761 | n/a | fds = array.array("i") |
---|
2762 | n/a | fds.frombytes(cmsg_data[: |
---|
2763 | n/a | len(cmsg_data) - (len(cmsg_data) % fds.itemsize)]) |
---|
2764 | n/a | for fd in fds: |
---|
2765 | n/a | os.close(fd) |
---|
2766 | n/a | |
---|
2767 | n/a | def createAndSendFDs(self, n): |
---|
2768 | n/a | # Send n new file descriptors created by newFDs() to the |
---|
2769 | n/a | # server, with the constant MSG as the non-ancillary data. |
---|
2770 | n/a | self.assertEqual( |
---|
2771 | n/a | self.sendmsgToServer([MSG], |
---|
2772 | n/a | [(socket.SOL_SOCKET, |
---|
2773 | n/a | socket.SCM_RIGHTS, |
---|
2774 | n/a | array.array("i", self.newFDs(n)))]), |
---|
2775 | n/a | len(MSG)) |
---|
2776 | n/a | |
---|
2777 | n/a | def checkRecvmsgFDs(self, numfds, result, maxcmsgs=1, ignoreflags=0): |
---|
2778 | n/a | # Check that constant MSG was received with numfds file |
---|
2779 | n/a | # descriptors in a maximum of maxcmsgs control messages (which |
---|
2780 | n/a | # must contain only complete integers). By default, check |
---|
2781 | n/a | # that MSG_CTRUNC is unset, but ignore any flags in |
---|
2782 | n/a | # ignoreflags. |
---|
2783 | n/a | msg, ancdata, flags, addr = result |
---|
2784 | n/a | self.assertEqual(msg, MSG) |
---|
2785 | n/a | self.checkRecvmsgAddress(addr, self.cli_addr) |
---|
2786 | n/a | self.checkFlags(flags, eor=True, checkunset=socket.MSG_CTRUNC, |
---|
2787 | n/a | ignore=ignoreflags) |
---|
2788 | n/a | |
---|
2789 | n/a | self.assertIsInstance(ancdata, list) |
---|
2790 | n/a | self.assertLessEqual(len(ancdata), maxcmsgs) |
---|
2791 | n/a | fds = array.array("i") |
---|
2792 | n/a | for item in ancdata: |
---|
2793 | n/a | self.assertIsInstance(item, tuple) |
---|
2794 | n/a | cmsg_level, cmsg_type, cmsg_data = item |
---|
2795 | n/a | self.assertEqual(cmsg_level, socket.SOL_SOCKET) |
---|
2796 | n/a | self.assertEqual(cmsg_type, socket.SCM_RIGHTS) |
---|
2797 | n/a | self.assertIsInstance(cmsg_data, bytes) |
---|
2798 | n/a | self.assertEqual(len(cmsg_data) % SIZEOF_INT, 0) |
---|
2799 | n/a | fds.frombytes(cmsg_data) |
---|
2800 | n/a | |
---|
2801 | n/a | self.assertEqual(len(fds), numfds) |
---|
2802 | n/a | self.checkFDs(fds) |
---|
2803 | n/a | |
---|
2804 | n/a | def testFDPassSimple(self): |
---|
2805 | n/a | # Pass a single FD (array read from bytes object). |
---|
2806 | n/a | self.checkRecvmsgFDs(1, self.doRecvmsg(self.serv_sock, |
---|
2807 | n/a | len(MSG), 10240)) |
---|
2808 | n/a | |
---|
2809 | n/a | def _testFDPassSimple(self): |
---|
2810 | n/a | self.assertEqual( |
---|
2811 | n/a | self.sendmsgToServer( |
---|
2812 | n/a | [MSG], |
---|
2813 | n/a | [(socket.SOL_SOCKET, |
---|
2814 | n/a | socket.SCM_RIGHTS, |
---|
2815 | n/a | array.array("i", self.newFDs(1)).tobytes())]), |
---|
2816 | n/a | len(MSG)) |
---|
2817 | n/a | |
---|
2818 | n/a | def testMultipleFDPass(self): |
---|
2819 | n/a | # Pass multiple FDs in a single array. |
---|
2820 | n/a | self.checkRecvmsgFDs(4, self.doRecvmsg(self.serv_sock, |
---|
2821 | n/a | len(MSG), 10240)) |
---|
2822 | n/a | |
---|
2823 | n/a | def _testMultipleFDPass(self): |
---|
2824 | n/a | self.createAndSendFDs(4) |
---|
2825 | n/a | |
---|
2826 | n/a | @requireAttrs(socket, "CMSG_SPACE") |
---|
2827 | n/a | def testFDPassCMSG_SPACE(self): |
---|
2828 | n/a | # Test using CMSG_SPACE() to calculate ancillary buffer size. |
---|
2829 | n/a | self.checkRecvmsgFDs( |
---|
2830 | n/a | 4, self.doRecvmsg(self.serv_sock, len(MSG), |
---|
2831 | n/a | socket.CMSG_SPACE(4 * SIZEOF_INT))) |
---|
2832 | n/a | |
---|
2833 | n/a | @testFDPassCMSG_SPACE.client_skip |
---|
2834 | n/a | def _testFDPassCMSG_SPACE(self): |
---|
2835 | n/a | self.createAndSendFDs(4) |
---|
2836 | n/a | |
---|
2837 | n/a | def testFDPassCMSG_LEN(self): |
---|
2838 | n/a | # Test using CMSG_LEN() to calculate ancillary buffer size. |
---|
2839 | n/a | self.checkRecvmsgFDs(1, |
---|
2840 | n/a | self.doRecvmsg(self.serv_sock, len(MSG), |
---|
2841 | n/a | socket.CMSG_LEN(4 * SIZEOF_INT)), |
---|
2842 | n/a | # RFC 3542 says implementations may set |
---|
2843 | n/a | # MSG_CTRUNC if there isn't enough space |
---|
2844 | n/a | # for trailing padding. |
---|
2845 | n/a | ignoreflags=socket.MSG_CTRUNC) |
---|
2846 | n/a | |
---|
2847 | n/a | def _testFDPassCMSG_LEN(self): |
---|
2848 | n/a | self.createAndSendFDs(1) |
---|
2849 | n/a | |
---|
2850 | n/a | @unittest.skipIf(sys.platform == "darwin", "skipping, see issue #12958") |
---|
2851 | n/a | @unittest.skipIf(sys.platform.startswith("aix"), "skipping, see issue #22397") |
---|
2852 | n/a | @requireAttrs(socket, "CMSG_SPACE") |
---|
2853 | n/a | def testFDPassSeparate(self): |
---|
2854 | n/a | # Pass two FDs in two separate arrays. Arrays may be combined |
---|
2855 | n/a | # into a single control message by the OS. |
---|
2856 | n/a | self.checkRecvmsgFDs(2, |
---|
2857 | n/a | self.doRecvmsg(self.serv_sock, len(MSG), 10240), |
---|
2858 | n/a | maxcmsgs=2) |
---|
2859 | n/a | |
---|
2860 | n/a | @testFDPassSeparate.client_skip |
---|
2861 | n/a | @unittest.skipIf(sys.platform == "darwin", "skipping, see issue #12958") |
---|
2862 | n/a | @unittest.skipIf(sys.platform.startswith("aix"), "skipping, see issue #22397") |
---|
2863 | n/a | def _testFDPassSeparate(self): |
---|
2864 | n/a | fd0, fd1 = self.newFDs(2) |
---|
2865 | n/a | self.assertEqual( |
---|
2866 | n/a | self.sendmsgToServer([MSG], [(socket.SOL_SOCKET, |
---|
2867 | n/a | socket.SCM_RIGHTS, |
---|
2868 | n/a | array.array("i", [fd0])), |
---|
2869 | n/a | (socket.SOL_SOCKET, |
---|
2870 | n/a | socket.SCM_RIGHTS, |
---|
2871 | n/a | array.array("i", [fd1]))]), |
---|
2872 | n/a | len(MSG)) |
---|
2873 | n/a | |
---|
2874 | n/a | @unittest.skipIf(sys.platform == "darwin", "skipping, see issue #12958") |
---|
2875 | n/a | @unittest.skipIf(sys.platform.startswith("aix"), "skipping, see issue #22397") |
---|
2876 | n/a | @requireAttrs(socket, "CMSG_SPACE") |
---|
2877 | n/a | def testFDPassSeparateMinSpace(self): |
---|
2878 | n/a | # Pass two FDs in two separate arrays, receiving them into the |
---|
2879 | n/a | # minimum space for two arrays. |
---|
2880 | n/a | self.checkRecvmsgFDs(2, |
---|
2881 | n/a | self.doRecvmsg(self.serv_sock, len(MSG), |
---|
2882 | n/a | socket.CMSG_SPACE(SIZEOF_INT) + |
---|
2883 | n/a | socket.CMSG_LEN(SIZEOF_INT)), |
---|
2884 | n/a | maxcmsgs=2, ignoreflags=socket.MSG_CTRUNC) |
---|
2885 | n/a | |
---|
2886 | n/a | @testFDPassSeparateMinSpace.client_skip |
---|
2887 | n/a | @unittest.skipIf(sys.platform == "darwin", "skipping, see issue #12958") |
---|
2888 | n/a | @unittest.skipIf(sys.platform.startswith("aix"), "skipping, see issue #22397") |
---|
2889 | n/a | def _testFDPassSeparateMinSpace(self): |
---|
2890 | n/a | fd0, fd1 = self.newFDs(2) |
---|
2891 | n/a | self.assertEqual( |
---|
2892 | n/a | self.sendmsgToServer([MSG], [(socket.SOL_SOCKET, |
---|
2893 | n/a | socket.SCM_RIGHTS, |
---|
2894 | n/a | array.array("i", [fd0])), |
---|
2895 | n/a | (socket.SOL_SOCKET, |
---|
2896 | n/a | socket.SCM_RIGHTS, |
---|
2897 | n/a | array.array("i", [fd1]))]), |
---|
2898 | n/a | len(MSG)) |
---|
2899 | n/a | |
---|
2900 | n/a | def sendAncillaryIfPossible(self, msg, ancdata): |
---|
2901 | n/a | # Try to send msg and ancdata to server, but if the system |
---|
2902 | n/a | # call fails, just send msg with no ancillary data. |
---|
2903 | n/a | try: |
---|
2904 | n/a | nbytes = self.sendmsgToServer([msg], ancdata) |
---|
2905 | n/a | except OSError as e: |
---|
2906 | n/a | # Check that it was the system call that failed |
---|
2907 | n/a | self.assertIsInstance(e.errno, int) |
---|
2908 | n/a | nbytes = self.sendmsgToServer([msg]) |
---|
2909 | n/a | self.assertEqual(nbytes, len(msg)) |
---|
2910 | n/a | |
---|
2911 | n/a | @unittest.skipIf(sys.platform == "darwin", "see issue #24725") |
---|
2912 | n/a | def testFDPassEmpty(self): |
---|
2913 | n/a | # Try to pass an empty FD array. Can receive either no array |
---|
2914 | n/a | # or an empty array. |
---|
2915 | n/a | self.checkRecvmsgFDs(0, self.doRecvmsg(self.serv_sock, |
---|
2916 | n/a | len(MSG), 10240), |
---|
2917 | n/a | ignoreflags=socket.MSG_CTRUNC) |
---|
2918 | n/a | |
---|
2919 | n/a | def _testFDPassEmpty(self): |
---|
2920 | n/a | self.sendAncillaryIfPossible(MSG, [(socket.SOL_SOCKET, |
---|
2921 | n/a | socket.SCM_RIGHTS, |
---|
2922 | n/a | b"")]) |
---|
2923 | n/a | |
---|
2924 | n/a | def testFDPassPartialInt(self): |
---|
2925 | n/a | # Try to pass a truncated FD array. |
---|
2926 | n/a | msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, |
---|
2927 | n/a | len(MSG), 10240) |
---|
2928 | n/a | self.assertEqual(msg, MSG) |
---|
2929 | n/a | self.checkRecvmsgAddress(addr, self.cli_addr) |
---|
2930 | n/a | self.checkFlags(flags, eor=True, ignore=socket.MSG_CTRUNC) |
---|
2931 | n/a | self.assertLessEqual(len(ancdata), 1) |
---|
2932 | n/a | for cmsg_level, cmsg_type, cmsg_data in ancdata: |
---|
2933 | n/a | self.assertEqual(cmsg_level, socket.SOL_SOCKET) |
---|
2934 | n/a | self.assertEqual(cmsg_type, socket.SCM_RIGHTS) |
---|
2935 | n/a | self.assertLess(len(cmsg_data), SIZEOF_INT) |
---|
2936 | n/a | |
---|
2937 | n/a | def _testFDPassPartialInt(self): |
---|
2938 | n/a | self.sendAncillaryIfPossible( |
---|
2939 | n/a | MSG, |
---|
2940 | n/a | [(socket.SOL_SOCKET, |
---|
2941 | n/a | socket.SCM_RIGHTS, |
---|
2942 | n/a | array.array("i", [self.badfd]).tobytes()[:-1])]) |
---|
2943 | n/a | |
---|
2944 | n/a | @requireAttrs(socket, "CMSG_SPACE") |
---|
2945 | n/a | def testFDPassPartialIntInMiddle(self): |
---|
2946 | n/a | # Try to pass two FD arrays, the first of which is truncated. |
---|
2947 | n/a | msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, |
---|
2948 | n/a | len(MSG), 10240) |
---|
2949 | n/a | self.assertEqual(msg, MSG) |
---|
2950 | n/a | self.checkRecvmsgAddress(addr, self.cli_addr) |
---|
2951 | n/a | self.checkFlags(flags, eor=True, ignore=socket.MSG_CTRUNC) |
---|
2952 | n/a | self.assertLessEqual(len(ancdata), 2) |
---|
2953 | n/a | fds = array.array("i") |
---|
2954 | n/a | # Arrays may have been combined in a single control message |
---|
2955 | n/a | for cmsg_level, cmsg_type, cmsg_data in ancdata: |
---|
2956 | n/a | self.assertEqual(cmsg_level, socket.SOL_SOCKET) |
---|
2957 | n/a | self.assertEqual(cmsg_type, socket.SCM_RIGHTS) |
---|
2958 | n/a | fds.frombytes(cmsg_data[: |
---|
2959 | n/a | len(cmsg_data) - (len(cmsg_data) % fds.itemsize)]) |
---|
2960 | n/a | self.assertLessEqual(len(fds), 2) |
---|
2961 | n/a | self.checkFDs(fds) |
---|
2962 | n/a | |
---|
2963 | n/a | @testFDPassPartialIntInMiddle.client_skip |
---|
2964 | n/a | def _testFDPassPartialIntInMiddle(self): |
---|
2965 | n/a | fd0, fd1 = self.newFDs(2) |
---|
2966 | n/a | self.sendAncillaryIfPossible( |
---|
2967 | n/a | MSG, |
---|
2968 | n/a | [(socket.SOL_SOCKET, |
---|
2969 | n/a | socket.SCM_RIGHTS, |
---|
2970 | n/a | array.array("i", [fd0, self.badfd]).tobytes()[:-1]), |
---|
2971 | n/a | (socket.SOL_SOCKET, |
---|
2972 | n/a | socket.SCM_RIGHTS, |
---|
2973 | n/a | array.array("i", [fd1]))]) |
---|
2974 | n/a | |
---|
2975 | n/a | def checkTruncatedHeader(self, result, ignoreflags=0): |
---|
2976 | n/a | # Check that no ancillary data items are returned when data is |
---|
2977 | n/a | # truncated inside the cmsghdr structure. |
---|
2978 | n/a | msg, ancdata, flags, addr = result |
---|
2979 | n/a | self.assertEqual(msg, MSG) |
---|
2980 | n/a | self.checkRecvmsgAddress(addr, self.cli_addr) |
---|
2981 | n/a | self.assertEqual(ancdata, []) |
---|
2982 | n/a | self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC, |
---|
2983 | n/a | ignore=ignoreflags) |
---|
2984 | n/a | |
---|
2985 | n/a | def testCmsgTruncNoBufSize(self): |
---|
2986 | n/a | # Check that no ancillary data is received when no buffer size |
---|
2987 | n/a | # is specified. |
---|
2988 | n/a | self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG)), |
---|
2989 | n/a | # BSD seems to set MSG_CTRUNC only |
---|
2990 | n/a | # if an item has been partially |
---|
2991 | n/a | # received. |
---|
2992 | n/a | ignoreflags=socket.MSG_CTRUNC) |
---|
2993 | n/a | |
---|
2994 | n/a | def _testCmsgTruncNoBufSize(self): |
---|
2995 | n/a | self.createAndSendFDs(1) |
---|
2996 | n/a | |
---|
2997 | n/a | def testCmsgTrunc0(self): |
---|
2998 | n/a | # Check that no ancillary data is received when buffer size is 0. |
---|
2999 | n/a | self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG), 0), |
---|
3000 | n/a | ignoreflags=socket.MSG_CTRUNC) |
---|
3001 | n/a | |
---|
3002 | n/a | def _testCmsgTrunc0(self): |
---|
3003 | n/a | self.createAndSendFDs(1) |
---|
3004 | n/a | |
---|
3005 | n/a | # Check that no ancillary data is returned for various non-zero |
---|
3006 | n/a | # (but still too small) buffer sizes. |
---|
3007 | n/a | |
---|
3008 | n/a | def testCmsgTrunc1(self): |
---|
3009 | n/a | self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG), 1)) |
---|
3010 | n/a | |
---|
3011 | n/a | def _testCmsgTrunc1(self): |
---|
3012 | n/a | self.createAndSendFDs(1) |
---|
3013 | n/a | |
---|
3014 | n/a | def testCmsgTrunc2Int(self): |
---|
3015 | n/a | # The cmsghdr structure has at least three members, two of |
---|
3016 | n/a | # which are ints, so we still shouldn't see any ancillary |
---|
3017 | n/a | # data. |
---|
3018 | n/a | self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG), |
---|
3019 | n/a | SIZEOF_INT * 2)) |
---|
3020 | n/a | |
---|
3021 | n/a | def _testCmsgTrunc2Int(self): |
---|
3022 | n/a | self.createAndSendFDs(1) |
---|
3023 | n/a | |
---|
3024 | n/a | def testCmsgTruncLen0Minus1(self): |
---|
3025 | n/a | self.checkTruncatedHeader(self.doRecvmsg(self.serv_sock, len(MSG), |
---|
3026 | n/a | socket.CMSG_LEN(0) - 1)) |
---|
3027 | n/a | |
---|
3028 | n/a | def _testCmsgTruncLen0Minus1(self): |
---|
3029 | n/a | self.createAndSendFDs(1) |
---|
3030 | n/a | |
---|
3031 | n/a | # The following tests try to truncate the control message in the |
---|
3032 | n/a | # middle of the FD array. |
---|
3033 | n/a | |
---|
3034 | n/a | def checkTruncatedArray(self, ancbuf, maxdata, mindata=0): |
---|
3035 | n/a | # Check that file descriptor data is truncated to between |
---|
3036 | n/a | # mindata and maxdata bytes when received with buffer size |
---|
3037 | n/a | # ancbuf, and that any complete file descriptor numbers are |
---|
3038 | n/a | # valid. |
---|
3039 | n/a | msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, |
---|
3040 | n/a | len(MSG), ancbuf) |
---|
3041 | n/a | self.assertEqual(msg, MSG) |
---|
3042 | n/a | self.checkRecvmsgAddress(addr, self.cli_addr) |
---|
3043 | n/a | self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC) |
---|
3044 | n/a | |
---|
3045 | n/a | if mindata == 0 and ancdata == []: |
---|
3046 | n/a | return |
---|
3047 | n/a | self.assertEqual(len(ancdata), 1) |
---|
3048 | n/a | cmsg_level, cmsg_type, cmsg_data = ancdata[0] |
---|
3049 | n/a | self.assertEqual(cmsg_level, socket.SOL_SOCKET) |
---|
3050 | n/a | self.assertEqual(cmsg_type, socket.SCM_RIGHTS) |
---|
3051 | n/a | self.assertGreaterEqual(len(cmsg_data), mindata) |
---|
3052 | n/a | self.assertLessEqual(len(cmsg_data), maxdata) |
---|
3053 | n/a | fds = array.array("i") |
---|
3054 | n/a | fds.frombytes(cmsg_data[: |
---|
3055 | n/a | len(cmsg_data) - (len(cmsg_data) % fds.itemsize)]) |
---|
3056 | n/a | self.checkFDs(fds) |
---|
3057 | n/a | |
---|
3058 | n/a | def testCmsgTruncLen0(self): |
---|
3059 | n/a | self.checkTruncatedArray(ancbuf=socket.CMSG_LEN(0), maxdata=0) |
---|
3060 | n/a | |
---|
3061 | n/a | def _testCmsgTruncLen0(self): |
---|
3062 | n/a | self.createAndSendFDs(1) |
---|
3063 | n/a | |
---|
3064 | n/a | def testCmsgTruncLen0Plus1(self): |
---|
3065 | n/a | self.checkTruncatedArray(ancbuf=socket.CMSG_LEN(0) + 1, maxdata=1) |
---|
3066 | n/a | |
---|
3067 | n/a | def _testCmsgTruncLen0Plus1(self): |
---|
3068 | n/a | self.createAndSendFDs(2) |
---|
3069 | n/a | |
---|
3070 | n/a | def testCmsgTruncLen1(self): |
---|
3071 | n/a | self.checkTruncatedArray(ancbuf=socket.CMSG_LEN(SIZEOF_INT), |
---|
3072 | n/a | maxdata=SIZEOF_INT) |
---|
3073 | n/a | |
---|
3074 | n/a | def _testCmsgTruncLen1(self): |
---|
3075 | n/a | self.createAndSendFDs(2) |
---|
3076 | n/a | |
---|
3077 | n/a | def testCmsgTruncLen2Minus1(self): |
---|
3078 | n/a | self.checkTruncatedArray(ancbuf=socket.CMSG_LEN(2 * SIZEOF_INT) - 1, |
---|
3079 | n/a | maxdata=(2 * SIZEOF_INT) - 1) |
---|
3080 | n/a | |
---|
3081 | n/a | def _testCmsgTruncLen2Minus1(self): |
---|
3082 | n/a | self.createAndSendFDs(2) |
---|
3083 | n/a | |
---|
3084 | n/a | |
---|
3085 | n/a | class RFC3542AncillaryTest(SendrecvmsgServerTimeoutBase): |
---|
3086 | n/a | # Test sendmsg() and recvmsg[_into]() using the ancillary data |
---|
3087 | n/a | # features of the RFC 3542 Advanced Sockets API for IPv6. |
---|
3088 | n/a | # Currently we can only handle certain data items (e.g. traffic |
---|
3089 | n/a | # class, hop limit, MTU discovery and fragmentation settings) |
---|
3090 | n/a | # without resorting to unportable means such as the struct module, |
---|
3091 | n/a | # but the tests here are aimed at testing the ancillary data |
---|
3092 | n/a | # handling in sendmsg() and recvmsg() rather than the IPv6 API |
---|
3093 | n/a | # itself. |
---|
3094 | n/a | |
---|
3095 | n/a | # Test value to use when setting hop limit of packet |
---|
3096 | n/a | hop_limit = 2 |
---|
3097 | n/a | |
---|
3098 | n/a | # Test value to use when setting traffic class of packet. |
---|
3099 | n/a | # -1 means "use kernel default". |
---|
3100 | n/a | traffic_class = -1 |
---|
3101 | n/a | |
---|
3102 | n/a | def ancillaryMapping(self, ancdata): |
---|
3103 | n/a | # Given ancillary data list ancdata, return a mapping from |
---|
3104 | n/a | # pairs (cmsg_level, cmsg_type) to corresponding cmsg_data. |
---|
3105 | n/a | # Check that no (level, type) pair appears more than once. |
---|
3106 | n/a | d = {} |
---|
3107 | n/a | for cmsg_level, cmsg_type, cmsg_data in ancdata: |
---|
3108 | n/a | self.assertNotIn((cmsg_level, cmsg_type), d) |
---|
3109 | n/a | d[(cmsg_level, cmsg_type)] = cmsg_data |
---|
3110 | n/a | return d |
---|
3111 | n/a | |
---|
3112 | n/a | def checkHopLimit(self, ancbufsize, maxhop=255, ignoreflags=0): |
---|
3113 | n/a | # Receive hop limit into ancbufsize bytes of ancillary data |
---|
3114 | n/a | # space. Check that data is MSG, ancillary data is not |
---|
3115 | n/a | # truncated (but ignore any flags in ignoreflags), and hop |
---|
3116 | n/a | # limit is between 0 and maxhop inclusive. |
---|
3117 | n/a | self.serv_sock.setsockopt(socket.IPPROTO_IPV6, |
---|
3118 | n/a | socket.IPV6_RECVHOPLIMIT, 1) |
---|
3119 | n/a | self.misc_event.set() |
---|
3120 | n/a | msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, |
---|
3121 | n/a | len(MSG), ancbufsize) |
---|
3122 | n/a | |
---|
3123 | n/a | self.assertEqual(msg, MSG) |
---|
3124 | n/a | self.checkRecvmsgAddress(addr, self.cli_addr) |
---|
3125 | n/a | self.checkFlags(flags, eor=True, checkunset=socket.MSG_CTRUNC, |
---|
3126 | n/a | ignore=ignoreflags) |
---|
3127 | n/a | |
---|
3128 | n/a | self.assertEqual(len(ancdata), 1) |
---|
3129 | n/a | self.assertIsInstance(ancdata[0], tuple) |
---|
3130 | n/a | cmsg_level, cmsg_type, cmsg_data = ancdata[0] |
---|
3131 | n/a | self.assertEqual(cmsg_level, socket.IPPROTO_IPV6) |
---|
3132 | n/a | self.assertEqual(cmsg_type, socket.IPV6_HOPLIMIT) |
---|
3133 | n/a | self.assertIsInstance(cmsg_data, bytes) |
---|
3134 | n/a | self.assertEqual(len(cmsg_data), SIZEOF_INT) |
---|
3135 | n/a | a = array.array("i") |
---|
3136 | n/a | a.frombytes(cmsg_data) |
---|
3137 | n/a | self.assertGreaterEqual(a[0], 0) |
---|
3138 | n/a | self.assertLessEqual(a[0], maxhop) |
---|
3139 | n/a | |
---|
3140 | n/a | @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT") |
---|
3141 | n/a | def testRecvHopLimit(self): |
---|
3142 | n/a | # Test receiving the packet hop limit as ancillary data. |
---|
3143 | n/a | self.checkHopLimit(ancbufsize=10240) |
---|
3144 | n/a | |
---|
3145 | n/a | @testRecvHopLimit.client_skip |
---|
3146 | n/a | def _testRecvHopLimit(self): |
---|
3147 | n/a | # Need to wait until server has asked to receive ancillary |
---|
3148 | n/a | # data, as implementations are not required to buffer it |
---|
3149 | n/a | # otherwise. |
---|
3150 | n/a | self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
---|
3151 | n/a | self.sendToServer(MSG) |
---|
3152 | n/a | |
---|
3153 | n/a | @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT") |
---|
3154 | n/a | def testRecvHopLimitCMSG_SPACE(self): |
---|
3155 | n/a | # Test receiving hop limit, using CMSG_SPACE to calculate buffer size. |
---|
3156 | n/a | self.checkHopLimit(ancbufsize=socket.CMSG_SPACE(SIZEOF_INT)) |
---|
3157 | n/a | |
---|
3158 | n/a | @testRecvHopLimitCMSG_SPACE.client_skip |
---|
3159 | n/a | def _testRecvHopLimitCMSG_SPACE(self): |
---|
3160 | n/a | self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
---|
3161 | n/a | self.sendToServer(MSG) |
---|
3162 | n/a | |
---|
3163 | n/a | # Could test receiving into buffer sized using CMSG_LEN, but RFC |
---|
3164 | n/a | # 3542 says portable applications must provide space for trailing |
---|
3165 | n/a | # padding. Implementations may set MSG_CTRUNC if there isn't |
---|
3166 | n/a | # enough space for the padding. |
---|
3167 | n/a | |
---|
3168 | n/a | @requireAttrs(socket.socket, "sendmsg") |
---|
3169 | n/a | @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT") |
---|
3170 | n/a | def testSetHopLimit(self): |
---|
3171 | n/a | # Test setting hop limit on outgoing packet and receiving it |
---|
3172 | n/a | # at the other end. |
---|
3173 | n/a | self.checkHopLimit(ancbufsize=10240, maxhop=self.hop_limit) |
---|
3174 | n/a | |
---|
3175 | n/a | @testSetHopLimit.client_skip |
---|
3176 | n/a | def _testSetHopLimit(self): |
---|
3177 | n/a | self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
---|
3178 | n/a | self.assertEqual( |
---|
3179 | n/a | self.sendmsgToServer([MSG], |
---|
3180 | n/a | [(socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT, |
---|
3181 | n/a | array.array("i", [self.hop_limit]))]), |
---|
3182 | n/a | len(MSG)) |
---|
3183 | n/a | |
---|
3184 | n/a | def checkTrafficClassAndHopLimit(self, ancbufsize, maxhop=255, |
---|
3185 | n/a | ignoreflags=0): |
---|
3186 | n/a | # Receive traffic class and hop limit into ancbufsize bytes of |
---|
3187 | n/a | # ancillary data space. Check that data is MSG, ancillary |
---|
3188 | n/a | # data is not truncated (but ignore any flags in ignoreflags), |
---|
3189 | n/a | # and traffic class and hop limit are in range (hop limit no |
---|
3190 | n/a | # more than maxhop). |
---|
3191 | n/a | self.serv_sock.setsockopt(socket.IPPROTO_IPV6, |
---|
3192 | n/a | socket.IPV6_RECVHOPLIMIT, 1) |
---|
3193 | n/a | self.serv_sock.setsockopt(socket.IPPROTO_IPV6, |
---|
3194 | n/a | socket.IPV6_RECVTCLASS, 1) |
---|
3195 | n/a | self.misc_event.set() |
---|
3196 | n/a | msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, |
---|
3197 | n/a | len(MSG), ancbufsize) |
---|
3198 | n/a | |
---|
3199 | n/a | self.assertEqual(msg, MSG) |
---|
3200 | n/a | self.checkRecvmsgAddress(addr, self.cli_addr) |
---|
3201 | n/a | self.checkFlags(flags, eor=True, checkunset=socket.MSG_CTRUNC, |
---|
3202 | n/a | ignore=ignoreflags) |
---|
3203 | n/a | self.assertEqual(len(ancdata), 2) |
---|
3204 | n/a | ancmap = self.ancillaryMapping(ancdata) |
---|
3205 | n/a | |
---|
3206 | n/a | tcdata = ancmap[(socket.IPPROTO_IPV6, socket.IPV6_TCLASS)] |
---|
3207 | n/a | self.assertEqual(len(tcdata), SIZEOF_INT) |
---|
3208 | n/a | a = array.array("i") |
---|
3209 | n/a | a.frombytes(tcdata) |
---|
3210 | n/a | self.assertGreaterEqual(a[0], 0) |
---|
3211 | n/a | self.assertLessEqual(a[0], 255) |
---|
3212 | n/a | |
---|
3213 | n/a | hldata = ancmap[(socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT)] |
---|
3214 | n/a | self.assertEqual(len(hldata), SIZEOF_INT) |
---|
3215 | n/a | a = array.array("i") |
---|
3216 | n/a | a.frombytes(hldata) |
---|
3217 | n/a | self.assertGreaterEqual(a[0], 0) |
---|
3218 | n/a | self.assertLessEqual(a[0], maxhop) |
---|
3219 | n/a | |
---|
3220 | n/a | @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT", |
---|
3221 | n/a | "IPV6_RECVTCLASS", "IPV6_TCLASS") |
---|
3222 | n/a | def testRecvTrafficClassAndHopLimit(self): |
---|
3223 | n/a | # Test receiving traffic class and hop limit as ancillary data. |
---|
3224 | n/a | self.checkTrafficClassAndHopLimit(ancbufsize=10240) |
---|
3225 | n/a | |
---|
3226 | n/a | @testRecvTrafficClassAndHopLimit.client_skip |
---|
3227 | n/a | def _testRecvTrafficClassAndHopLimit(self): |
---|
3228 | n/a | self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
---|
3229 | n/a | self.sendToServer(MSG) |
---|
3230 | n/a | |
---|
3231 | n/a | @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT", |
---|
3232 | n/a | "IPV6_RECVTCLASS", "IPV6_TCLASS") |
---|
3233 | n/a | def testRecvTrafficClassAndHopLimitCMSG_SPACE(self): |
---|
3234 | n/a | # Test receiving traffic class and hop limit, using |
---|
3235 | n/a | # CMSG_SPACE() to calculate buffer size. |
---|
3236 | n/a | self.checkTrafficClassAndHopLimit( |
---|
3237 | n/a | ancbufsize=socket.CMSG_SPACE(SIZEOF_INT) * 2) |
---|
3238 | n/a | |
---|
3239 | n/a | @testRecvTrafficClassAndHopLimitCMSG_SPACE.client_skip |
---|
3240 | n/a | def _testRecvTrafficClassAndHopLimitCMSG_SPACE(self): |
---|
3241 | n/a | self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
---|
3242 | n/a | self.sendToServer(MSG) |
---|
3243 | n/a | |
---|
3244 | n/a | @requireAttrs(socket.socket, "sendmsg") |
---|
3245 | n/a | @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT", |
---|
3246 | n/a | "IPV6_RECVTCLASS", "IPV6_TCLASS") |
---|
3247 | n/a | def testSetTrafficClassAndHopLimit(self): |
---|
3248 | n/a | # Test setting traffic class and hop limit on outgoing packet, |
---|
3249 | n/a | # and receiving them at the other end. |
---|
3250 | n/a | self.checkTrafficClassAndHopLimit(ancbufsize=10240, |
---|
3251 | n/a | maxhop=self.hop_limit) |
---|
3252 | n/a | |
---|
3253 | n/a | @testSetTrafficClassAndHopLimit.client_skip |
---|
3254 | n/a | def _testSetTrafficClassAndHopLimit(self): |
---|
3255 | n/a | self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
---|
3256 | n/a | self.assertEqual( |
---|
3257 | n/a | self.sendmsgToServer([MSG], |
---|
3258 | n/a | [(socket.IPPROTO_IPV6, socket.IPV6_TCLASS, |
---|
3259 | n/a | array.array("i", [self.traffic_class])), |
---|
3260 | n/a | (socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT, |
---|
3261 | n/a | array.array("i", [self.hop_limit]))]), |
---|
3262 | n/a | len(MSG)) |
---|
3263 | n/a | |
---|
3264 | n/a | @requireAttrs(socket.socket, "sendmsg") |
---|
3265 | n/a | @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT", |
---|
3266 | n/a | "IPV6_RECVTCLASS", "IPV6_TCLASS") |
---|
3267 | n/a | def testOddCmsgSize(self): |
---|
3268 | n/a | # Try to send ancillary data with first item one byte too |
---|
3269 | n/a | # long. Fall back to sending with correct size if this fails, |
---|
3270 | n/a | # and check that second item was handled correctly. |
---|
3271 | n/a | self.checkTrafficClassAndHopLimit(ancbufsize=10240, |
---|
3272 | n/a | maxhop=self.hop_limit) |
---|
3273 | n/a | |
---|
3274 | n/a | @testOddCmsgSize.client_skip |
---|
3275 | n/a | def _testOddCmsgSize(self): |
---|
3276 | n/a | self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
---|
3277 | n/a | try: |
---|
3278 | n/a | nbytes = self.sendmsgToServer( |
---|
3279 | n/a | [MSG], |
---|
3280 | n/a | [(socket.IPPROTO_IPV6, socket.IPV6_TCLASS, |
---|
3281 | n/a | array.array("i", [self.traffic_class]).tobytes() + b"\x00"), |
---|
3282 | n/a | (socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT, |
---|
3283 | n/a | array.array("i", [self.hop_limit]))]) |
---|
3284 | n/a | except OSError as e: |
---|
3285 | n/a | self.assertIsInstance(e.errno, int) |
---|
3286 | n/a | nbytes = self.sendmsgToServer( |
---|
3287 | n/a | [MSG], |
---|
3288 | n/a | [(socket.IPPROTO_IPV6, socket.IPV6_TCLASS, |
---|
3289 | n/a | array.array("i", [self.traffic_class])), |
---|
3290 | n/a | (socket.IPPROTO_IPV6, socket.IPV6_HOPLIMIT, |
---|
3291 | n/a | array.array("i", [self.hop_limit]))]) |
---|
3292 | n/a | self.assertEqual(nbytes, len(MSG)) |
---|
3293 | n/a | |
---|
3294 | n/a | # Tests for proper handling of truncated ancillary data |
---|
3295 | n/a | |
---|
3296 | n/a | def checkHopLimitTruncatedHeader(self, ancbufsize, ignoreflags=0): |
---|
3297 | n/a | # Receive hop limit into ancbufsize bytes of ancillary data |
---|
3298 | n/a | # space, which should be too small to contain the ancillary |
---|
3299 | n/a | # data header (if ancbufsize is None, pass no second argument |
---|
3300 | n/a | # to recvmsg()). Check that data is MSG, MSG_CTRUNC is set |
---|
3301 | n/a | # (unless included in ignoreflags), and no ancillary data is |
---|
3302 | n/a | # returned. |
---|
3303 | n/a | self.serv_sock.setsockopt(socket.IPPROTO_IPV6, |
---|
3304 | n/a | socket.IPV6_RECVHOPLIMIT, 1) |
---|
3305 | n/a | self.misc_event.set() |
---|
3306 | n/a | args = () if ancbufsize is None else (ancbufsize,) |
---|
3307 | n/a | msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, |
---|
3308 | n/a | len(MSG), *args) |
---|
3309 | n/a | |
---|
3310 | n/a | self.assertEqual(msg, MSG) |
---|
3311 | n/a | self.checkRecvmsgAddress(addr, self.cli_addr) |
---|
3312 | n/a | self.assertEqual(ancdata, []) |
---|
3313 | n/a | self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC, |
---|
3314 | n/a | ignore=ignoreflags) |
---|
3315 | n/a | |
---|
3316 | n/a | @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT") |
---|
3317 | n/a | def testCmsgTruncNoBufSize(self): |
---|
3318 | n/a | # Check that no ancillary data is received when no ancillary |
---|
3319 | n/a | # buffer size is provided. |
---|
3320 | n/a | self.checkHopLimitTruncatedHeader(ancbufsize=None, |
---|
3321 | n/a | # BSD seems to set |
---|
3322 | n/a | # MSG_CTRUNC only if an item |
---|
3323 | n/a | # has been partially |
---|
3324 | n/a | # received. |
---|
3325 | n/a | ignoreflags=socket.MSG_CTRUNC) |
---|
3326 | n/a | |
---|
3327 | n/a | @testCmsgTruncNoBufSize.client_skip |
---|
3328 | n/a | def _testCmsgTruncNoBufSize(self): |
---|
3329 | n/a | self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
---|
3330 | n/a | self.sendToServer(MSG) |
---|
3331 | n/a | |
---|
3332 | n/a | @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT") |
---|
3333 | n/a | def testSingleCmsgTrunc0(self): |
---|
3334 | n/a | # Check that no ancillary data is received when ancillary |
---|
3335 | n/a | # buffer size is zero. |
---|
3336 | n/a | self.checkHopLimitTruncatedHeader(ancbufsize=0, |
---|
3337 | n/a | ignoreflags=socket.MSG_CTRUNC) |
---|
3338 | n/a | |
---|
3339 | n/a | @testSingleCmsgTrunc0.client_skip |
---|
3340 | n/a | def _testSingleCmsgTrunc0(self): |
---|
3341 | n/a | self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
---|
3342 | n/a | self.sendToServer(MSG) |
---|
3343 | n/a | |
---|
3344 | n/a | # Check that no ancillary data is returned for various non-zero |
---|
3345 | n/a | # (but still too small) buffer sizes. |
---|
3346 | n/a | |
---|
3347 | n/a | @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT") |
---|
3348 | n/a | def testSingleCmsgTrunc1(self): |
---|
3349 | n/a | self.checkHopLimitTruncatedHeader(ancbufsize=1) |
---|
3350 | n/a | |
---|
3351 | n/a | @testSingleCmsgTrunc1.client_skip |
---|
3352 | n/a | def _testSingleCmsgTrunc1(self): |
---|
3353 | n/a | self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
---|
3354 | n/a | self.sendToServer(MSG) |
---|
3355 | n/a | |
---|
3356 | n/a | @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT") |
---|
3357 | n/a | def testSingleCmsgTrunc2Int(self): |
---|
3358 | n/a | self.checkHopLimitTruncatedHeader(ancbufsize=2 * SIZEOF_INT) |
---|
3359 | n/a | |
---|
3360 | n/a | @testSingleCmsgTrunc2Int.client_skip |
---|
3361 | n/a | def _testSingleCmsgTrunc2Int(self): |
---|
3362 | n/a | self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
---|
3363 | n/a | self.sendToServer(MSG) |
---|
3364 | n/a | |
---|
3365 | n/a | @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT") |
---|
3366 | n/a | def testSingleCmsgTruncLen0Minus1(self): |
---|
3367 | n/a | self.checkHopLimitTruncatedHeader(ancbufsize=socket.CMSG_LEN(0) - 1) |
---|
3368 | n/a | |
---|
3369 | n/a | @testSingleCmsgTruncLen0Minus1.client_skip |
---|
3370 | n/a | def _testSingleCmsgTruncLen0Minus1(self): |
---|
3371 | n/a | self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
---|
3372 | n/a | self.sendToServer(MSG) |
---|
3373 | n/a | |
---|
3374 | n/a | @requireAttrs(socket, "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT") |
---|
3375 | n/a | def testSingleCmsgTruncInData(self): |
---|
3376 | n/a | # Test truncation of a control message inside its associated |
---|
3377 | n/a | # data. The message may be returned with its data truncated, |
---|
3378 | n/a | # or not returned at all. |
---|
3379 | n/a | self.serv_sock.setsockopt(socket.IPPROTO_IPV6, |
---|
3380 | n/a | socket.IPV6_RECVHOPLIMIT, 1) |
---|
3381 | n/a | self.misc_event.set() |
---|
3382 | n/a | msg, ancdata, flags, addr = self.doRecvmsg( |
---|
3383 | n/a | self.serv_sock, len(MSG), socket.CMSG_LEN(SIZEOF_INT) - 1) |
---|
3384 | n/a | |
---|
3385 | n/a | self.assertEqual(msg, MSG) |
---|
3386 | n/a | self.checkRecvmsgAddress(addr, self.cli_addr) |
---|
3387 | n/a | self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC) |
---|
3388 | n/a | |
---|
3389 | n/a | self.assertLessEqual(len(ancdata), 1) |
---|
3390 | n/a | if ancdata: |
---|
3391 | n/a | cmsg_level, cmsg_type, cmsg_data = ancdata[0] |
---|
3392 | n/a | self.assertEqual(cmsg_level, socket.IPPROTO_IPV6) |
---|
3393 | n/a | self.assertEqual(cmsg_type, socket.IPV6_HOPLIMIT) |
---|
3394 | n/a | self.assertLess(len(cmsg_data), SIZEOF_INT) |
---|
3395 | n/a | |
---|
3396 | n/a | @testSingleCmsgTruncInData.client_skip |
---|
3397 | n/a | def _testSingleCmsgTruncInData(self): |
---|
3398 | n/a | self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
---|
3399 | n/a | self.sendToServer(MSG) |
---|
3400 | n/a | |
---|
3401 | n/a | def checkTruncatedSecondHeader(self, ancbufsize, ignoreflags=0): |
---|
3402 | n/a | # Receive traffic class and hop limit into ancbufsize bytes of |
---|
3403 | n/a | # ancillary data space, which should be large enough to |
---|
3404 | n/a | # contain the first item, but too small to contain the header |
---|
3405 | n/a | # of the second. Check that data is MSG, MSG_CTRUNC is set |
---|
3406 | n/a | # (unless included in ignoreflags), and only one ancillary |
---|
3407 | n/a | # data item is returned. |
---|
3408 | n/a | self.serv_sock.setsockopt(socket.IPPROTO_IPV6, |
---|
3409 | n/a | socket.IPV6_RECVHOPLIMIT, 1) |
---|
3410 | n/a | self.serv_sock.setsockopt(socket.IPPROTO_IPV6, |
---|
3411 | n/a | socket.IPV6_RECVTCLASS, 1) |
---|
3412 | n/a | self.misc_event.set() |
---|
3413 | n/a | msg, ancdata, flags, addr = self.doRecvmsg(self.serv_sock, |
---|
3414 | n/a | len(MSG), ancbufsize) |
---|
3415 | n/a | |
---|
3416 | n/a | self.assertEqual(msg, MSG) |
---|
3417 | n/a | self.checkRecvmsgAddress(addr, self.cli_addr) |
---|
3418 | n/a | self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC, |
---|
3419 | n/a | ignore=ignoreflags) |
---|
3420 | n/a | |
---|
3421 | n/a | self.assertEqual(len(ancdata), 1) |
---|
3422 | n/a | cmsg_level, cmsg_type, cmsg_data = ancdata[0] |
---|
3423 | n/a | self.assertEqual(cmsg_level, socket.IPPROTO_IPV6) |
---|
3424 | n/a | self.assertIn(cmsg_type, {socket.IPV6_TCLASS, socket.IPV6_HOPLIMIT}) |
---|
3425 | n/a | self.assertEqual(len(cmsg_data), SIZEOF_INT) |
---|
3426 | n/a | a = array.array("i") |
---|
3427 | n/a | a.frombytes(cmsg_data) |
---|
3428 | n/a | self.assertGreaterEqual(a[0], 0) |
---|
3429 | n/a | self.assertLessEqual(a[0], 255) |
---|
3430 | n/a | |
---|
3431 | n/a | # Try the above test with various buffer sizes. |
---|
3432 | n/a | |
---|
3433 | n/a | @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT", |
---|
3434 | n/a | "IPV6_RECVTCLASS", "IPV6_TCLASS") |
---|
3435 | n/a | def testSecondCmsgTrunc0(self): |
---|
3436 | n/a | self.checkTruncatedSecondHeader(socket.CMSG_SPACE(SIZEOF_INT), |
---|
3437 | n/a | ignoreflags=socket.MSG_CTRUNC) |
---|
3438 | n/a | |
---|
3439 | n/a | @testSecondCmsgTrunc0.client_skip |
---|
3440 | n/a | def _testSecondCmsgTrunc0(self): |
---|
3441 | n/a | self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
---|
3442 | n/a | self.sendToServer(MSG) |
---|
3443 | n/a | |
---|
3444 | n/a | @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT", |
---|
3445 | n/a | "IPV6_RECVTCLASS", "IPV6_TCLASS") |
---|
3446 | n/a | def testSecondCmsgTrunc1(self): |
---|
3447 | n/a | self.checkTruncatedSecondHeader(socket.CMSG_SPACE(SIZEOF_INT) + 1) |
---|
3448 | n/a | |
---|
3449 | n/a | @testSecondCmsgTrunc1.client_skip |
---|
3450 | n/a | def _testSecondCmsgTrunc1(self): |
---|
3451 | n/a | self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
---|
3452 | n/a | self.sendToServer(MSG) |
---|
3453 | n/a | |
---|
3454 | n/a | @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT", |
---|
3455 | n/a | "IPV6_RECVTCLASS", "IPV6_TCLASS") |
---|
3456 | n/a | def testSecondCmsgTrunc2Int(self): |
---|
3457 | n/a | self.checkTruncatedSecondHeader(socket.CMSG_SPACE(SIZEOF_INT) + |
---|
3458 | n/a | 2 * SIZEOF_INT) |
---|
3459 | n/a | |
---|
3460 | n/a | @testSecondCmsgTrunc2Int.client_skip |
---|
3461 | n/a | def _testSecondCmsgTrunc2Int(self): |
---|
3462 | n/a | self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
---|
3463 | n/a | self.sendToServer(MSG) |
---|
3464 | n/a | |
---|
3465 | n/a | @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT", |
---|
3466 | n/a | "IPV6_RECVTCLASS", "IPV6_TCLASS") |
---|
3467 | n/a | def testSecondCmsgTruncLen0Minus1(self): |
---|
3468 | n/a | self.checkTruncatedSecondHeader(socket.CMSG_SPACE(SIZEOF_INT) + |
---|
3469 | n/a | socket.CMSG_LEN(0) - 1) |
---|
3470 | n/a | |
---|
3471 | n/a | @testSecondCmsgTruncLen0Minus1.client_skip |
---|
3472 | n/a | def _testSecondCmsgTruncLen0Minus1(self): |
---|
3473 | n/a | self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
---|
3474 | n/a | self.sendToServer(MSG) |
---|
3475 | n/a | |
---|
3476 | n/a | @requireAttrs(socket, "CMSG_SPACE", "IPV6_RECVHOPLIMIT", "IPV6_HOPLIMIT", |
---|
3477 | n/a | "IPV6_RECVTCLASS", "IPV6_TCLASS") |
---|
3478 | n/a | def testSecomdCmsgTruncInData(self): |
---|
3479 | n/a | # Test truncation of the second of two control messages inside |
---|
3480 | n/a | # its associated data. |
---|
3481 | n/a | self.serv_sock.setsockopt(socket.IPPROTO_IPV6, |
---|
3482 | n/a | socket.IPV6_RECVHOPLIMIT, 1) |
---|
3483 | n/a | self.serv_sock.setsockopt(socket.IPPROTO_IPV6, |
---|
3484 | n/a | socket.IPV6_RECVTCLASS, 1) |
---|
3485 | n/a | self.misc_event.set() |
---|
3486 | n/a | msg, ancdata, flags, addr = self.doRecvmsg( |
---|
3487 | n/a | self.serv_sock, len(MSG), |
---|
3488 | n/a | socket.CMSG_SPACE(SIZEOF_INT) + socket.CMSG_LEN(SIZEOF_INT) - 1) |
---|
3489 | n/a | |
---|
3490 | n/a | self.assertEqual(msg, MSG) |
---|
3491 | n/a | self.checkRecvmsgAddress(addr, self.cli_addr) |
---|
3492 | n/a | self.checkFlags(flags, eor=True, checkset=socket.MSG_CTRUNC) |
---|
3493 | n/a | |
---|
3494 | n/a | cmsg_types = {socket.IPV6_TCLASS, socket.IPV6_HOPLIMIT} |
---|
3495 | n/a | |
---|
3496 | n/a | cmsg_level, cmsg_type, cmsg_data = ancdata.pop(0) |
---|
3497 | n/a | self.assertEqual(cmsg_level, socket.IPPROTO_IPV6) |
---|
3498 | n/a | cmsg_types.remove(cmsg_type) |
---|
3499 | n/a | self.assertEqual(len(cmsg_data), SIZEOF_INT) |
---|
3500 | n/a | a = array.array("i") |
---|
3501 | n/a | a.frombytes(cmsg_data) |
---|
3502 | n/a | self.assertGreaterEqual(a[0], 0) |
---|
3503 | n/a | self.assertLessEqual(a[0], 255) |
---|
3504 | n/a | |
---|
3505 | n/a | if ancdata: |
---|
3506 | n/a | cmsg_level, cmsg_type, cmsg_data = ancdata.pop(0) |
---|
3507 | n/a | self.assertEqual(cmsg_level, socket.IPPROTO_IPV6) |
---|
3508 | n/a | cmsg_types.remove(cmsg_type) |
---|
3509 | n/a | self.assertLess(len(cmsg_data), SIZEOF_INT) |
---|
3510 | n/a | |
---|
3511 | n/a | self.assertEqual(ancdata, []) |
---|
3512 | n/a | |
---|
3513 | n/a | @testSecomdCmsgTruncInData.client_skip |
---|
3514 | n/a | def _testSecomdCmsgTruncInData(self): |
---|
3515 | n/a | self.assertTrue(self.misc_event.wait(timeout=self.fail_timeout)) |
---|
3516 | n/a | self.sendToServer(MSG) |
---|
3517 | n/a | |
---|
3518 | n/a | |
---|
3519 | n/a | # Derive concrete test classes for different socket types. |
---|
3520 | n/a | |
---|
3521 | n/a | class SendrecvmsgUDPTestBase(SendrecvmsgDgramFlagsBase, |
---|
3522 | n/a | SendrecvmsgConnectionlessBase, |
---|
3523 | n/a | ThreadedSocketTestMixin, UDPTestBase): |
---|
3524 | n/a | pass |
---|
3525 | n/a | |
---|
3526 | n/a | @requireAttrs(socket.socket, "sendmsg") |
---|
3527 | n/a | @unittest.skipUnless(thread, 'Threading required for this test.') |
---|
3528 | n/a | class SendmsgUDPTest(SendmsgConnectionlessTests, SendrecvmsgUDPTestBase): |
---|
3529 | n/a | pass |
---|
3530 | n/a | |
---|
3531 | n/a | @requireAttrs(socket.socket, "recvmsg") |
---|
3532 | n/a | @unittest.skipUnless(thread, 'Threading required for this test.') |
---|
3533 | n/a | class RecvmsgUDPTest(RecvmsgTests, SendrecvmsgUDPTestBase): |
---|
3534 | n/a | pass |
---|
3535 | n/a | |
---|
3536 | n/a | @requireAttrs(socket.socket, "recvmsg_into") |
---|
3537 | n/a | @unittest.skipUnless(thread, 'Threading required for this test.') |
---|
3538 | n/a | class RecvmsgIntoUDPTest(RecvmsgIntoTests, SendrecvmsgUDPTestBase): |
---|
3539 | n/a | pass |
---|
3540 | n/a | |
---|
3541 | n/a | |
---|
3542 | n/a | class SendrecvmsgUDP6TestBase(SendrecvmsgDgramFlagsBase, |
---|
3543 | n/a | SendrecvmsgConnectionlessBase, |
---|
3544 | n/a | ThreadedSocketTestMixin, UDP6TestBase): |
---|
3545 | n/a | |
---|
3546 | n/a | def checkRecvmsgAddress(self, addr1, addr2): |
---|
3547 | n/a | # Called to compare the received address with the address of |
---|
3548 | n/a | # the peer, ignoring scope ID |
---|
3549 | n/a | self.assertEqual(addr1[:-1], addr2[:-1]) |
---|
3550 | n/a | |
---|
3551 | n/a | @requireAttrs(socket.socket, "sendmsg") |
---|
3552 | n/a | @unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.') |
---|
3553 | n/a | @requireSocket("AF_INET6", "SOCK_DGRAM") |
---|
3554 | n/a | @unittest.skipUnless(thread, 'Threading required for this test.') |
---|
3555 | n/a | class SendmsgUDP6Test(SendmsgConnectionlessTests, SendrecvmsgUDP6TestBase): |
---|
3556 | n/a | pass |
---|
3557 | n/a | |
---|
3558 | n/a | @requireAttrs(socket.socket, "recvmsg") |
---|
3559 | n/a | @unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.') |
---|
3560 | n/a | @requireSocket("AF_INET6", "SOCK_DGRAM") |
---|
3561 | n/a | @unittest.skipUnless(thread, 'Threading required for this test.') |
---|
3562 | n/a | class RecvmsgUDP6Test(RecvmsgTests, SendrecvmsgUDP6TestBase): |
---|
3563 | n/a | pass |
---|
3564 | n/a | |
---|
3565 | n/a | @requireAttrs(socket.socket, "recvmsg_into") |
---|
3566 | n/a | @unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.') |
---|
3567 | n/a | @requireSocket("AF_INET6", "SOCK_DGRAM") |
---|
3568 | n/a | @unittest.skipUnless(thread, 'Threading required for this test.') |
---|
3569 | n/a | class RecvmsgIntoUDP6Test(RecvmsgIntoTests, SendrecvmsgUDP6TestBase): |
---|
3570 | n/a | pass |
---|
3571 | n/a | |
---|
3572 | n/a | @requireAttrs(socket.socket, "recvmsg") |
---|
3573 | n/a | @unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.') |
---|
3574 | n/a | @requireAttrs(socket, "IPPROTO_IPV6") |
---|
3575 | n/a | @requireSocket("AF_INET6", "SOCK_DGRAM") |
---|
3576 | n/a | @unittest.skipUnless(thread, 'Threading required for this test.') |
---|
3577 | n/a | class RecvmsgRFC3542AncillaryUDP6Test(RFC3542AncillaryTest, |
---|
3578 | n/a | SendrecvmsgUDP6TestBase): |
---|
3579 | n/a | pass |
---|
3580 | n/a | |
---|
3581 | n/a | @requireAttrs(socket.socket, "recvmsg_into") |
---|
3582 | n/a | @unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.') |
---|
3583 | n/a | @requireAttrs(socket, "IPPROTO_IPV6") |
---|
3584 | n/a | @requireSocket("AF_INET6", "SOCK_DGRAM") |
---|
3585 | n/a | @unittest.skipUnless(thread, 'Threading required for this test.') |
---|
3586 | n/a | class RecvmsgIntoRFC3542AncillaryUDP6Test(RecvmsgIntoMixin, |
---|
3587 | n/a | RFC3542AncillaryTest, |
---|
3588 | n/a | SendrecvmsgUDP6TestBase): |
---|
3589 | n/a | pass |
---|
3590 | n/a | |
---|
3591 | n/a | |
---|
3592 | n/a | class SendrecvmsgTCPTestBase(SendrecvmsgConnectedBase, |
---|
3593 | n/a | ConnectedStreamTestMixin, TCPTestBase): |
---|
3594 | n/a | pass |
---|
3595 | n/a | |
---|
3596 | n/a | @requireAttrs(socket.socket, "sendmsg") |
---|
3597 | n/a | @unittest.skipUnless(thread, 'Threading required for this test.') |
---|
3598 | n/a | class SendmsgTCPTest(SendmsgStreamTests, SendrecvmsgTCPTestBase): |
---|
3599 | n/a | pass |
---|
3600 | n/a | |
---|
3601 | n/a | @requireAttrs(socket.socket, "recvmsg") |
---|
3602 | n/a | @unittest.skipUnless(thread, 'Threading required for this test.') |
---|
3603 | n/a | class RecvmsgTCPTest(RecvmsgTests, RecvmsgGenericStreamTests, |
---|
3604 | n/a | SendrecvmsgTCPTestBase): |
---|
3605 | n/a | pass |
---|
3606 | n/a | |
---|
3607 | n/a | @requireAttrs(socket.socket, "recvmsg_into") |
---|
3608 | n/a | @unittest.skipUnless(thread, 'Threading required for this test.') |
---|
3609 | n/a | class RecvmsgIntoTCPTest(RecvmsgIntoTests, RecvmsgGenericStreamTests, |
---|
3610 | n/a | SendrecvmsgTCPTestBase): |
---|
3611 | n/a | pass |
---|
3612 | n/a | |
---|
3613 | n/a | |
---|
3614 | n/a | class SendrecvmsgSCTPStreamTestBase(SendrecvmsgSCTPFlagsBase, |
---|
3615 | n/a | SendrecvmsgConnectedBase, |
---|
3616 | n/a | ConnectedStreamTestMixin, SCTPStreamBase): |
---|
3617 | n/a | pass |
---|
3618 | n/a | |
---|
3619 | n/a | @requireAttrs(socket.socket, "sendmsg") |
---|
3620 | n/a | @requireSocket("AF_INET", "SOCK_STREAM", "IPPROTO_SCTP") |
---|
3621 | n/a | @unittest.skipUnless(thread, 'Threading required for this test.') |
---|
3622 | n/a | class SendmsgSCTPStreamTest(SendmsgStreamTests, SendrecvmsgSCTPStreamTestBase): |
---|
3623 | n/a | pass |
---|
3624 | n/a | |
---|
3625 | n/a | @requireAttrs(socket.socket, "recvmsg") |
---|
3626 | n/a | @requireSocket("AF_INET", "SOCK_STREAM", "IPPROTO_SCTP") |
---|
3627 | n/a | @unittest.skipUnless(thread, 'Threading required for this test.') |
---|
3628 | n/a | class RecvmsgSCTPStreamTest(RecvmsgTests, RecvmsgGenericStreamTests, |
---|
3629 | n/a | SendrecvmsgSCTPStreamTestBase): |
---|
3630 | n/a | |
---|
3631 | n/a | def testRecvmsgEOF(self): |
---|
3632 | n/a | try: |
---|
3633 | n/a | super(RecvmsgSCTPStreamTest, self).testRecvmsgEOF() |
---|
3634 | n/a | except OSError as e: |
---|
3635 | n/a | if e.errno != errno.ENOTCONN: |
---|
3636 | n/a | raise |
---|
3637 | n/a | self.skipTest("sporadic ENOTCONN (kernel issue?) - see issue #13876") |
---|
3638 | n/a | |
---|
3639 | n/a | @requireAttrs(socket.socket, "recvmsg_into") |
---|
3640 | n/a | @requireSocket("AF_INET", "SOCK_STREAM", "IPPROTO_SCTP") |
---|
3641 | n/a | @unittest.skipUnless(thread, 'Threading required for this test.') |
---|
3642 | n/a | class RecvmsgIntoSCTPStreamTest(RecvmsgIntoTests, RecvmsgGenericStreamTests, |
---|
3643 | n/a | SendrecvmsgSCTPStreamTestBase): |
---|
3644 | n/a | |
---|
3645 | n/a | def testRecvmsgEOF(self): |
---|
3646 | n/a | try: |
---|
3647 | n/a | super(RecvmsgIntoSCTPStreamTest, self).testRecvmsgEOF() |
---|
3648 | n/a | except OSError as e: |
---|
3649 | n/a | if e.errno != errno.ENOTCONN: |
---|
3650 | n/a | raise |
---|
3651 | n/a | self.skipTest("sporadic ENOTCONN (kernel issue?) - see issue #13876") |
---|
3652 | n/a | |
---|
3653 | n/a | |
---|
3654 | n/a | class SendrecvmsgUnixStreamTestBase(SendrecvmsgConnectedBase, |
---|
3655 | n/a | ConnectedStreamTestMixin, UnixStreamBase): |
---|
3656 | n/a | pass |
---|
3657 | n/a | |
---|
3658 | n/a | @requireAttrs(socket.socket, "sendmsg") |
---|
3659 | n/a | @requireAttrs(socket, "AF_UNIX") |
---|
3660 | n/a | @unittest.skipUnless(thread, 'Threading required for this test.') |
---|
3661 | n/a | class SendmsgUnixStreamTest(SendmsgStreamTests, SendrecvmsgUnixStreamTestBase): |
---|
3662 | n/a | pass |
---|
3663 | n/a | |
---|
3664 | n/a | @requireAttrs(socket.socket, "recvmsg") |
---|
3665 | n/a | @requireAttrs(socket, "AF_UNIX") |
---|
3666 | n/a | @unittest.skipUnless(thread, 'Threading required for this test.') |
---|
3667 | n/a | class RecvmsgUnixStreamTest(RecvmsgTests, RecvmsgGenericStreamTests, |
---|
3668 | n/a | SendrecvmsgUnixStreamTestBase): |
---|
3669 | n/a | pass |
---|
3670 | n/a | |
---|
3671 | n/a | @requireAttrs(socket.socket, "recvmsg_into") |
---|
3672 | n/a | @requireAttrs(socket, "AF_UNIX") |
---|
3673 | n/a | @unittest.skipUnless(thread, 'Threading required for this test.') |
---|
3674 | n/a | class RecvmsgIntoUnixStreamTest(RecvmsgIntoTests, RecvmsgGenericStreamTests, |
---|
3675 | n/a | SendrecvmsgUnixStreamTestBase): |
---|
3676 | n/a | pass |
---|
3677 | n/a | |
---|
3678 | n/a | @requireAttrs(socket.socket, "sendmsg", "recvmsg") |
---|
3679 | n/a | @requireAttrs(socket, "AF_UNIX", "SOL_SOCKET", "SCM_RIGHTS") |
---|
3680 | n/a | @unittest.skipUnless(thread, 'Threading required for this test.') |
---|
3681 | n/a | class RecvmsgSCMRightsStreamTest(SCMRightsTest, SendrecvmsgUnixStreamTestBase): |
---|
3682 | n/a | pass |
---|
3683 | n/a | |
---|
3684 | n/a | @requireAttrs(socket.socket, "sendmsg", "recvmsg_into") |
---|
3685 | n/a | @requireAttrs(socket, "AF_UNIX", "SOL_SOCKET", "SCM_RIGHTS") |
---|
3686 | n/a | @unittest.skipUnless(thread, 'Threading required for this test.') |
---|
3687 | n/a | class RecvmsgIntoSCMRightsStreamTest(RecvmsgIntoMixin, SCMRightsTest, |
---|
3688 | n/a | SendrecvmsgUnixStreamTestBase): |
---|
3689 | n/a | pass |
---|
3690 | n/a | |
---|
3691 | n/a | |
---|
3692 | n/a | # Test interrupting the interruptible send/receive methods with a |
---|
3693 | n/a | # signal when a timeout is set. These tests avoid having multiple |
---|
3694 | n/a | # threads alive during the test so that the OS cannot deliver the |
---|
3695 | n/a | # signal to the wrong one. |
---|
3696 | n/a | |
---|
3697 | n/a | class InterruptedTimeoutBase(unittest.TestCase): |
---|
3698 | n/a | # Base class for interrupted send/receive tests. Installs an |
---|
3699 | n/a | # empty handler for SIGALRM and removes it on teardown, along with |
---|
3700 | n/a | # any scheduled alarms. |
---|
3701 | n/a | |
---|
3702 | n/a | def setUp(self): |
---|
3703 | n/a | super().setUp() |
---|
3704 | n/a | orig_alrm_handler = signal.signal(signal.SIGALRM, |
---|
3705 | n/a | lambda signum, frame: 1 / 0) |
---|
3706 | n/a | self.addCleanup(signal.signal, signal.SIGALRM, orig_alrm_handler) |
---|
3707 | n/a | self.addCleanup(self.setAlarm, 0) |
---|
3708 | n/a | |
---|
3709 | n/a | # Timeout for socket operations |
---|
3710 | n/a | timeout = 4.0 |
---|
3711 | n/a | |
---|
3712 | n/a | # Provide setAlarm() method to schedule delivery of SIGALRM after |
---|
3713 | n/a | # given number of seconds, or cancel it if zero, and an |
---|
3714 | n/a | # appropriate time value to use. Use setitimer() if available. |
---|
3715 | n/a | if hasattr(signal, "setitimer"): |
---|
3716 | n/a | alarm_time = 0.05 |
---|
3717 | n/a | |
---|
3718 | n/a | def setAlarm(self, seconds): |
---|
3719 | n/a | signal.setitimer(signal.ITIMER_REAL, seconds) |
---|
3720 | n/a | else: |
---|
3721 | n/a | # Old systems may deliver the alarm up to one second early |
---|
3722 | n/a | alarm_time = 2 |
---|
3723 | n/a | |
---|
3724 | n/a | def setAlarm(self, seconds): |
---|
3725 | n/a | signal.alarm(seconds) |
---|
3726 | n/a | |
---|
3727 | n/a | |
---|
3728 | n/a | # Require siginterrupt() in order to ensure that system calls are |
---|
3729 | n/a | # interrupted by default. |
---|
3730 | n/a | @requireAttrs(signal, "siginterrupt") |
---|
3731 | n/a | @unittest.skipUnless(hasattr(signal, "alarm") or hasattr(signal, "setitimer"), |
---|
3732 | n/a | "Don't have signal.alarm or signal.setitimer") |
---|
3733 | n/a | class InterruptedRecvTimeoutTest(InterruptedTimeoutBase, UDPTestBase): |
---|
3734 | n/a | # Test interrupting the recv*() methods with signals when a |
---|
3735 | n/a | # timeout is set. |
---|
3736 | n/a | |
---|
3737 | n/a | def setUp(self): |
---|
3738 | n/a | super().setUp() |
---|
3739 | n/a | self.serv.settimeout(self.timeout) |
---|
3740 | n/a | |
---|
3741 | n/a | def checkInterruptedRecv(self, func, *args, **kwargs): |
---|
3742 | n/a | # Check that func(*args, **kwargs) raises |
---|
3743 | n/a | # errno of EINTR when interrupted by a signal. |
---|
3744 | n/a | self.setAlarm(self.alarm_time) |
---|
3745 | n/a | with self.assertRaises(ZeroDivisionError) as cm: |
---|
3746 | n/a | func(*args, **kwargs) |
---|
3747 | n/a | |
---|
3748 | n/a | def testInterruptedRecvTimeout(self): |
---|
3749 | n/a | self.checkInterruptedRecv(self.serv.recv, 1024) |
---|
3750 | n/a | |
---|
3751 | n/a | def testInterruptedRecvIntoTimeout(self): |
---|
3752 | n/a | self.checkInterruptedRecv(self.serv.recv_into, bytearray(1024)) |
---|
3753 | n/a | |
---|
3754 | n/a | def testInterruptedRecvfromTimeout(self): |
---|
3755 | n/a | self.checkInterruptedRecv(self.serv.recvfrom, 1024) |
---|
3756 | n/a | |
---|
3757 | n/a | def testInterruptedRecvfromIntoTimeout(self): |
---|
3758 | n/a | self.checkInterruptedRecv(self.serv.recvfrom_into, bytearray(1024)) |
---|
3759 | n/a | |
---|
3760 | n/a | @requireAttrs(socket.socket, "recvmsg") |
---|
3761 | n/a | def testInterruptedRecvmsgTimeout(self): |
---|
3762 | n/a | self.checkInterruptedRecv(self.serv.recvmsg, 1024) |
---|
3763 | n/a | |
---|
3764 | n/a | @requireAttrs(socket.socket, "recvmsg_into") |
---|
3765 | n/a | def testInterruptedRecvmsgIntoTimeout(self): |
---|
3766 | n/a | self.checkInterruptedRecv(self.serv.recvmsg_into, [bytearray(1024)]) |
---|
3767 | n/a | |
---|
3768 | n/a | |
---|
3769 | n/a | # Require siginterrupt() in order to ensure that system calls are |
---|
3770 | n/a | # interrupted by default. |
---|
3771 | n/a | @requireAttrs(signal, "siginterrupt") |
---|
3772 | n/a | @unittest.skipUnless(hasattr(signal, "alarm") or hasattr(signal, "setitimer"), |
---|
3773 | n/a | "Don't have signal.alarm or signal.setitimer") |
---|
3774 | n/a | @unittest.skipUnless(thread, 'Threading required for this test.') |
---|
3775 | n/a | class InterruptedSendTimeoutTest(InterruptedTimeoutBase, |
---|
3776 | n/a | ThreadSafeCleanupTestCase, |
---|
3777 | n/a | SocketListeningTestMixin, TCPTestBase): |
---|
3778 | n/a | # Test interrupting the interruptible send*() methods with signals |
---|
3779 | n/a | # when a timeout is set. |
---|
3780 | n/a | |
---|
3781 | n/a | def setUp(self): |
---|
3782 | n/a | super().setUp() |
---|
3783 | n/a | self.serv_conn = self.newSocket() |
---|
3784 | n/a | self.addCleanup(self.serv_conn.close) |
---|
3785 | n/a | # Use a thread to complete the connection, but wait for it to |
---|
3786 | n/a | # terminate before running the test, so that there is only one |
---|
3787 | n/a | # thread to accept the signal. |
---|
3788 | n/a | cli_thread = threading.Thread(target=self.doConnect) |
---|
3789 | n/a | cli_thread.start() |
---|
3790 | n/a | self.cli_conn, addr = self.serv.accept() |
---|
3791 | n/a | self.addCleanup(self.cli_conn.close) |
---|
3792 | n/a | cli_thread.join() |
---|
3793 | n/a | self.serv_conn.settimeout(self.timeout) |
---|
3794 | n/a | |
---|
3795 | n/a | def doConnect(self): |
---|
3796 | n/a | self.serv_conn.connect(self.serv_addr) |
---|
3797 | n/a | |
---|
3798 | n/a | def checkInterruptedSend(self, func, *args, **kwargs): |
---|
3799 | n/a | # Check that func(*args, **kwargs), run in a loop, raises |
---|
3800 | n/a | # OSError with an errno of EINTR when interrupted by a |
---|
3801 | n/a | # signal. |
---|
3802 | n/a | with self.assertRaises(ZeroDivisionError) as cm: |
---|
3803 | n/a | while True: |
---|
3804 | n/a | self.setAlarm(self.alarm_time) |
---|
3805 | n/a | func(*args, **kwargs) |
---|
3806 | n/a | |
---|
3807 | n/a | # Issue #12958: The following tests have problems on OS X prior to 10.7 |
---|
3808 | n/a | @support.requires_mac_ver(10, 7) |
---|
3809 | n/a | def testInterruptedSendTimeout(self): |
---|
3810 | n/a | self.checkInterruptedSend(self.serv_conn.send, b"a"*512) |
---|
3811 | n/a | |
---|
3812 | n/a | @support.requires_mac_ver(10, 7) |
---|
3813 | n/a | def testInterruptedSendtoTimeout(self): |
---|
3814 | n/a | # Passing an actual address here as Python's wrapper for |
---|
3815 | n/a | # sendto() doesn't allow passing a zero-length one; POSIX |
---|
3816 | n/a | # requires that the address is ignored since the socket is |
---|
3817 | n/a | # connection-mode, however. |
---|
3818 | n/a | self.checkInterruptedSend(self.serv_conn.sendto, b"a"*512, |
---|
3819 | n/a | self.serv_addr) |
---|
3820 | n/a | |
---|
3821 | n/a | @support.requires_mac_ver(10, 7) |
---|
3822 | n/a | @requireAttrs(socket.socket, "sendmsg") |
---|
3823 | n/a | def testInterruptedSendmsgTimeout(self): |
---|
3824 | n/a | self.checkInterruptedSend(self.serv_conn.sendmsg, [b"a"*512]) |
---|
3825 | n/a | |
---|
3826 | n/a | |
---|
3827 | n/a | @unittest.skipUnless(thread, 'Threading required for this test.') |
---|
3828 | n/a | class TCPCloserTest(ThreadedTCPSocketTest): |
---|
3829 | n/a | |
---|
3830 | n/a | def testClose(self): |
---|
3831 | n/a | conn, addr = self.serv.accept() |
---|
3832 | n/a | conn.close() |
---|
3833 | n/a | |
---|
3834 | n/a | sd = self.cli |
---|
3835 | n/a | read, write, err = select.select([sd], [], [], 1.0) |
---|
3836 | n/a | self.assertEqual(read, [sd]) |
---|
3837 | n/a | self.assertEqual(sd.recv(1), b'') |
---|
3838 | n/a | |
---|
3839 | n/a | # Calling close() many times should be safe. |
---|
3840 | n/a | conn.close() |
---|
3841 | n/a | conn.close() |
---|
3842 | n/a | |
---|
3843 | n/a | def _testClose(self): |
---|
3844 | n/a | self.cli.connect((HOST, self.port)) |
---|
3845 | n/a | time.sleep(1.0) |
---|
3846 | n/a | |
---|
3847 | n/a | @unittest.skipUnless(thread, 'Threading required for this test.') |
---|
3848 | n/a | class BasicSocketPairTest(SocketPairTest): |
---|
3849 | n/a | |
---|
3850 | n/a | def __init__(self, methodName='runTest'): |
---|
3851 | n/a | SocketPairTest.__init__(self, methodName=methodName) |
---|
3852 | n/a | |
---|
3853 | n/a | def _check_defaults(self, sock): |
---|
3854 | n/a | self.assertIsInstance(sock, socket.socket) |
---|
3855 | n/a | if hasattr(socket, 'AF_UNIX'): |
---|
3856 | n/a | self.assertEqual(sock.family, socket.AF_UNIX) |
---|
3857 | n/a | else: |
---|
3858 | n/a | self.assertEqual(sock.family, socket.AF_INET) |
---|
3859 | n/a | self.assertEqual(sock.type, socket.SOCK_STREAM) |
---|
3860 | n/a | self.assertEqual(sock.proto, 0) |
---|
3861 | n/a | |
---|
3862 | n/a | def _testDefaults(self): |
---|
3863 | n/a | self._check_defaults(self.cli) |
---|
3864 | n/a | |
---|
3865 | n/a | def testDefaults(self): |
---|
3866 | n/a | self._check_defaults(self.serv) |
---|
3867 | n/a | |
---|
3868 | n/a | def testRecv(self): |
---|
3869 | n/a | msg = self.serv.recv(1024) |
---|
3870 | n/a | self.assertEqual(msg, MSG) |
---|
3871 | n/a | |
---|
3872 | n/a | def _testRecv(self): |
---|
3873 | n/a | self.cli.send(MSG) |
---|
3874 | n/a | |
---|
3875 | n/a | def testSend(self): |
---|
3876 | n/a | self.serv.send(MSG) |
---|
3877 | n/a | |
---|
3878 | n/a | def _testSend(self): |
---|
3879 | n/a | msg = self.cli.recv(1024) |
---|
3880 | n/a | self.assertEqual(msg, MSG) |
---|
3881 | n/a | |
---|
3882 | n/a | @unittest.skipUnless(thread, 'Threading required for this test.') |
---|
3883 | n/a | class NonBlockingTCPTests(ThreadedTCPSocketTest): |
---|
3884 | n/a | |
---|
3885 | n/a | def __init__(self, methodName='runTest'): |
---|
3886 | n/a | ThreadedTCPSocketTest.__init__(self, methodName=methodName) |
---|
3887 | n/a | |
---|
3888 | n/a | def testSetBlocking(self): |
---|
3889 | n/a | # Testing whether set blocking works |
---|
3890 | n/a | self.serv.setblocking(True) |
---|
3891 | n/a | self.assertIsNone(self.serv.gettimeout()) |
---|
3892 | n/a | self.serv.setblocking(False) |
---|
3893 | n/a | self.assertEqual(self.serv.gettimeout(), 0.0) |
---|
3894 | n/a | start = time.time() |
---|
3895 | n/a | try: |
---|
3896 | n/a | self.serv.accept() |
---|
3897 | n/a | except OSError: |
---|
3898 | n/a | pass |
---|
3899 | n/a | end = time.time() |
---|
3900 | n/a | self.assertTrue((end - start) < 1.0, "Error setting non-blocking mode.") |
---|
3901 | n/a | |
---|
3902 | n/a | def _testSetBlocking(self): |
---|
3903 | n/a | pass |
---|
3904 | n/a | |
---|
3905 | n/a | @support.cpython_only |
---|
3906 | n/a | def testSetBlocking_overflow(self): |
---|
3907 | n/a | # Issue 15989 |
---|
3908 | n/a | import _testcapi |
---|
3909 | n/a | if _testcapi.UINT_MAX >= _testcapi.ULONG_MAX: |
---|
3910 | n/a | self.skipTest('needs UINT_MAX < ULONG_MAX') |
---|
3911 | n/a | self.serv.setblocking(False) |
---|
3912 | n/a | self.assertEqual(self.serv.gettimeout(), 0.0) |
---|
3913 | n/a | self.serv.setblocking(_testcapi.UINT_MAX + 1) |
---|
3914 | n/a | self.assertIsNone(self.serv.gettimeout()) |
---|
3915 | n/a | |
---|
3916 | n/a | _testSetBlocking_overflow = support.cpython_only(_testSetBlocking) |
---|
3917 | n/a | |
---|
3918 | n/a | @unittest.skipUnless(hasattr(socket, 'SOCK_NONBLOCK'), |
---|
3919 | n/a | 'test needs socket.SOCK_NONBLOCK') |
---|
3920 | n/a | @support.requires_linux_version(2, 6, 28) |
---|
3921 | n/a | def testInitNonBlocking(self): |
---|
3922 | n/a | # reinit server socket |
---|
3923 | n/a | self.serv.close() |
---|
3924 | n/a | self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM | |
---|
3925 | n/a | socket.SOCK_NONBLOCK) |
---|
3926 | n/a | self.port = support.bind_port(self.serv) |
---|
3927 | n/a | self.serv.listen() |
---|
3928 | n/a | # actual testing |
---|
3929 | n/a | start = time.time() |
---|
3930 | n/a | try: |
---|
3931 | n/a | self.serv.accept() |
---|
3932 | n/a | except OSError: |
---|
3933 | n/a | pass |
---|
3934 | n/a | end = time.time() |
---|
3935 | n/a | self.assertTrue((end - start) < 1.0, "Error creating with non-blocking mode.") |
---|
3936 | n/a | |
---|
3937 | n/a | def _testInitNonBlocking(self): |
---|
3938 | n/a | pass |
---|
3939 | n/a | |
---|
3940 | n/a | def testInheritFlags(self): |
---|
3941 | n/a | # Issue #7995: when calling accept() on a listening socket with a |
---|
3942 | n/a | # timeout, the resulting socket should not be non-blocking. |
---|
3943 | n/a | self.serv.settimeout(10) |
---|
3944 | n/a | try: |
---|
3945 | n/a | conn, addr = self.serv.accept() |
---|
3946 | n/a | message = conn.recv(len(MSG)) |
---|
3947 | n/a | finally: |
---|
3948 | n/a | conn.close() |
---|
3949 | n/a | self.serv.settimeout(None) |
---|
3950 | n/a | |
---|
3951 | n/a | def _testInheritFlags(self): |
---|
3952 | n/a | time.sleep(0.1) |
---|
3953 | n/a | self.cli.connect((HOST, self.port)) |
---|
3954 | n/a | time.sleep(0.5) |
---|
3955 | n/a | self.cli.send(MSG) |
---|
3956 | n/a | |
---|
3957 | n/a | def testAccept(self): |
---|
3958 | n/a | # Testing non-blocking accept |
---|
3959 | n/a | self.serv.setblocking(0) |
---|
3960 | n/a | try: |
---|
3961 | n/a | conn, addr = self.serv.accept() |
---|
3962 | n/a | except OSError: |
---|
3963 | n/a | pass |
---|
3964 | n/a | else: |
---|
3965 | n/a | self.fail("Error trying to do non-blocking accept.") |
---|
3966 | n/a | read, write, err = select.select([self.serv], [], []) |
---|
3967 | n/a | if self.serv in read: |
---|
3968 | n/a | conn, addr = self.serv.accept() |
---|
3969 | n/a | self.assertIsNone(conn.gettimeout()) |
---|
3970 | n/a | conn.close() |
---|
3971 | n/a | else: |
---|
3972 | n/a | self.fail("Error trying to do accept after select.") |
---|
3973 | n/a | |
---|
3974 | n/a | def _testAccept(self): |
---|
3975 | n/a | time.sleep(0.1) |
---|
3976 | n/a | self.cli.connect((HOST, self.port)) |
---|
3977 | n/a | |
---|
3978 | n/a | def testConnect(self): |
---|
3979 | n/a | # Testing non-blocking connect |
---|
3980 | n/a | conn, addr = self.serv.accept() |
---|
3981 | n/a | conn.close() |
---|
3982 | n/a | |
---|
3983 | n/a | def _testConnect(self): |
---|
3984 | n/a | self.cli.settimeout(10) |
---|
3985 | n/a | self.cli.connect((HOST, self.port)) |
---|
3986 | n/a | |
---|
3987 | n/a | def testRecv(self): |
---|
3988 | n/a | # Testing non-blocking recv |
---|
3989 | n/a | conn, addr = self.serv.accept() |
---|
3990 | n/a | conn.setblocking(0) |
---|
3991 | n/a | try: |
---|
3992 | n/a | msg = conn.recv(len(MSG)) |
---|
3993 | n/a | except OSError: |
---|
3994 | n/a | pass |
---|
3995 | n/a | else: |
---|
3996 | n/a | self.fail("Error trying to do non-blocking recv.") |
---|
3997 | n/a | read, write, err = select.select([conn], [], []) |
---|
3998 | n/a | if conn in read: |
---|
3999 | n/a | msg = conn.recv(len(MSG)) |
---|
4000 | n/a | conn.close() |
---|
4001 | n/a | self.assertEqual(msg, MSG) |
---|
4002 | n/a | else: |
---|
4003 | n/a | self.fail("Error during select call to non-blocking socket.") |
---|
4004 | n/a | |
---|
4005 | n/a | def _testRecv(self): |
---|
4006 | n/a | self.cli.connect((HOST, self.port)) |
---|
4007 | n/a | time.sleep(0.1) |
---|
4008 | n/a | self.cli.send(MSG) |
---|
4009 | n/a | |
---|
4010 | n/a | @unittest.skipUnless(thread, 'Threading required for this test.') |
---|
4011 | n/a | class FileObjectClassTestCase(SocketConnectedTest): |
---|
4012 | n/a | """Unit tests for the object returned by socket.makefile() |
---|
4013 | n/a | |
---|
4014 | n/a | self.read_file is the io object returned by makefile() on |
---|
4015 | n/a | the client connection. You can read from this file to |
---|
4016 | n/a | get output from the server. |
---|
4017 | n/a | |
---|
4018 | n/a | self.write_file is the io object returned by makefile() on the |
---|
4019 | n/a | server connection. You can write to this file to send output |
---|
4020 | n/a | to the client. |
---|
4021 | n/a | """ |
---|
4022 | n/a | |
---|
4023 | n/a | bufsize = -1 # Use default buffer size |
---|
4024 | n/a | encoding = 'utf-8' |
---|
4025 | n/a | errors = 'strict' |
---|
4026 | n/a | newline = None |
---|
4027 | n/a | |
---|
4028 | n/a | read_mode = 'rb' |
---|
4029 | n/a | read_msg = MSG |
---|
4030 | n/a | write_mode = 'wb' |
---|
4031 | n/a | write_msg = MSG |
---|
4032 | n/a | |
---|
4033 | n/a | def __init__(self, methodName='runTest'): |
---|
4034 | n/a | SocketConnectedTest.__init__(self, methodName=methodName) |
---|
4035 | n/a | |
---|
4036 | n/a | def setUp(self): |
---|
4037 | n/a | self.evt1, self.evt2, self.serv_finished, self.cli_finished = [ |
---|
4038 | n/a | threading.Event() for i in range(4)] |
---|
4039 | n/a | SocketConnectedTest.setUp(self) |
---|
4040 | n/a | self.read_file = self.cli_conn.makefile( |
---|
4041 | n/a | self.read_mode, self.bufsize, |
---|
4042 | n/a | encoding = self.encoding, |
---|
4043 | n/a | errors = self.errors, |
---|
4044 | n/a | newline = self.newline) |
---|
4045 | n/a | |
---|
4046 | n/a | def tearDown(self): |
---|
4047 | n/a | self.serv_finished.set() |
---|
4048 | n/a | self.read_file.close() |
---|
4049 | n/a | self.assertTrue(self.read_file.closed) |
---|
4050 | n/a | self.read_file = None |
---|
4051 | n/a | SocketConnectedTest.tearDown(self) |
---|
4052 | n/a | |
---|
4053 | n/a | def clientSetUp(self): |
---|
4054 | n/a | SocketConnectedTest.clientSetUp(self) |
---|
4055 | n/a | self.write_file = self.serv_conn.makefile( |
---|
4056 | n/a | self.write_mode, self.bufsize, |
---|
4057 | n/a | encoding = self.encoding, |
---|
4058 | n/a | errors = self.errors, |
---|
4059 | n/a | newline = self.newline) |
---|
4060 | n/a | |
---|
4061 | n/a | def clientTearDown(self): |
---|
4062 | n/a | self.cli_finished.set() |
---|
4063 | n/a | self.write_file.close() |
---|
4064 | n/a | self.assertTrue(self.write_file.closed) |
---|
4065 | n/a | self.write_file = None |
---|
4066 | n/a | SocketConnectedTest.clientTearDown(self) |
---|
4067 | n/a | |
---|
4068 | n/a | def testReadAfterTimeout(self): |
---|
4069 | n/a | # Issue #7322: A file object must disallow further reads |
---|
4070 | n/a | # after a timeout has occurred. |
---|
4071 | n/a | self.cli_conn.settimeout(1) |
---|
4072 | n/a | self.read_file.read(3) |
---|
4073 | n/a | # First read raises a timeout |
---|
4074 | n/a | self.assertRaises(socket.timeout, self.read_file.read, 1) |
---|
4075 | n/a | # Second read is disallowed |
---|
4076 | n/a | with self.assertRaises(OSError) as ctx: |
---|
4077 | n/a | self.read_file.read(1) |
---|
4078 | n/a | self.assertIn("cannot read from timed out object", str(ctx.exception)) |
---|
4079 | n/a | |
---|
4080 | n/a | def _testReadAfterTimeout(self): |
---|
4081 | n/a | self.write_file.write(self.write_msg[0:3]) |
---|
4082 | n/a | self.write_file.flush() |
---|
4083 | n/a | self.serv_finished.wait() |
---|
4084 | n/a | |
---|
4085 | n/a | def testSmallRead(self): |
---|
4086 | n/a | # Performing small file read test |
---|
4087 | n/a | first_seg = self.read_file.read(len(self.read_msg)-3) |
---|
4088 | n/a | second_seg = self.read_file.read(3) |
---|
4089 | n/a | msg = first_seg + second_seg |
---|
4090 | n/a | self.assertEqual(msg, self.read_msg) |
---|
4091 | n/a | |
---|
4092 | n/a | def _testSmallRead(self): |
---|
4093 | n/a | self.write_file.write(self.write_msg) |
---|
4094 | n/a | self.write_file.flush() |
---|
4095 | n/a | |
---|
4096 | n/a | def testFullRead(self): |
---|
4097 | n/a | # read until EOF |
---|
4098 | n/a | msg = self.read_file.read() |
---|
4099 | n/a | self.assertEqual(msg, self.read_msg) |
---|
4100 | n/a | |
---|
4101 | n/a | def _testFullRead(self): |
---|
4102 | n/a | self.write_file.write(self.write_msg) |
---|
4103 | n/a | self.write_file.close() |
---|
4104 | n/a | |
---|
4105 | n/a | def testUnbufferedRead(self): |
---|
4106 | n/a | # Performing unbuffered file read test |
---|
4107 | n/a | buf = type(self.read_msg)() |
---|
4108 | n/a | while 1: |
---|
4109 | n/a | char = self.read_file.read(1) |
---|
4110 | n/a | if not char: |
---|
4111 | n/a | break |
---|
4112 | n/a | buf += char |
---|
4113 | n/a | self.assertEqual(buf, self.read_msg) |
---|
4114 | n/a | |
---|
4115 | n/a | def _testUnbufferedRead(self): |
---|
4116 | n/a | self.write_file.write(self.write_msg) |
---|
4117 | n/a | self.write_file.flush() |
---|
4118 | n/a | |
---|
4119 | n/a | def testReadline(self): |
---|
4120 | n/a | # Performing file readline test |
---|
4121 | n/a | line = self.read_file.readline() |
---|
4122 | n/a | self.assertEqual(line, self.read_msg) |
---|
4123 | n/a | |
---|
4124 | n/a | def _testReadline(self): |
---|
4125 | n/a | self.write_file.write(self.write_msg) |
---|
4126 | n/a | self.write_file.flush() |
---|
4127 | n/a | |
---|
4128 | n/a | def testCloseAfterMakefile(self): |
---|
4129 | n/a | # The file returned by makefile should keep the socket open. |
---|
4130 | n/a | self.cli_conn.close() |
---|
4131 | n/a | # read until EOF |
---|
4132 | n/a | msg = self.read_file.read() |
---|
4133 | n/a | self.assertEqual(msg, self.read_msg) |
---|
4134 | n/a | |
---|
4135 | n/a | def _testCloseAfterMakefile(self): |
---|
4136 | n/a | self.write_file.write(self.write_msg) |
---|
4137 | n/a | self.write_file.flush() |
---|
4138 | n/a | |
---|
4139 | n/a | def testMakefileAfterMakefileClose(self): |
---|
4140 | n/a | self.read_file.close() |
---|
4141 | n/a | msg = self.cli_conn.recv(len(MSG)) |
---|
4142 | n/a | if isinstance(self.read_msg, str): |
---|
4143 | n/a | msg = msg.decode() |
---|
4144 | n/a | self.assertEqual(msg, self.read_msg) |
---|
4145 | n/a | |
---|
4146 | n/a | def _testMakefileAfterMakefileClose(self): |
---|
4147 | n/a | self.write_file.write(self.write_msg) |
---|
4148 | n/a | self.write_file.flush() |
---|
4149 | n/a | |
---|
4150 | n/a | def testClosedAttr(self): |
---|
4151 | n/a | self.assertTrue(not self.read_file.closed) |
---|
4152 | n/a | |
---|
4153 | n/a | def _testClosedAttr(self): |
---|
4154 | n/a | self.assertTrue(not self.write_file.closed) |
---|
4155 | n/a | |
---|
4156 | n/a | def testAttributes(self): |
---|
4157 | n/a | self.assertEqual(self.read_file.mode, self.read_mode) |
---|
4158 | n/a | self.assertEqual(self.read_file.name, self.cli_conn.fileno()) |
---|
4159 | n/a | |
---|
4160 | n/a | def _testAttributes(self): |
---|
4161 | n/a | self.assertEqual(self.write_file.mode, self.write_mode) |
---|
4162 | n/a | self.assertEqual(self.write_file.name, self.serv_conn.fileno()) |
---|
4163 | n/a | |
---|
4164 | n/a | def testRealClose(self): |
---|
4165 | n/a | self.read_file.close() |
---|
4166 | n/a | self.assertRaises(ValueError, self.read_file.fileno) |
---|
4167 | n/a | self.cli_conn.close() |
---|
4168 | n/a | self.assertRaises(OSError, self.cli_conn.getsockname) |
---|
4169 | n/a | |
---|
4170 | n/a | def _testRealClose(self): |
---|
4171 | n/a | pass |
---|
4172 | n/a | |
---|
4173 | n/a | |
---|
4174 | n/a | class UnbufferedFileObjectClassTestCase(FileObjectClassTestCase): |
---|
4175 | n/a | |
---|
4176 | n/a | """Repeat the tests from FileObjectClassTestCase with bufsize==0. |
---|
4177 | n/a | |
---|
4178 | n/a | In this case (and in this case only), it should be possible to |
---|
4179 | n/a | create a file object, read a line from it, create another file |
---|
4180 | n/a | object, read another line from it, without loss of data in the |
---|
4181 | n/a | first file object's buffer. Note that http.client relies on this |
---|
4182 | n/a | when reading multiple requests from the same socket.""" |
---|
4183 | n/a | |
---|
4184 | n/a | bufsize = 0 # Use unbuffered mode |
---|
4185 | n/a | |
---|
4186 | n/a | def testUnbufferedReadline(self): |
---|
4187 | n/a | # Read a line, create a new file object, read another line with it |
---|
4188 | n/a | line = self.read_file.readline() # first line |
---|
4189 | n/a | self.assertEqual(line, b"A. " + self.write_msg) # first line |
---|
4190 | n/a | self.read_file = self.cli_conn.makefile('rb', 0) |
---|
4191 | n/a | line = self.read_file.readline() # second line |
---|
4192 | n/a | self.assertEqual(line, b"B. " + self.write_msg) # second line |
---|
4193 | n/a | |
---|
4194 | n/a | def _testUnbufferedReadline(self): |
---|
4195 | n/a | self.write_file.write(b"A. " + self.write_msg) |
---|
4196 | n/a | self.write_file.write(b"B. " + self.write_msg) |
---|
4197 | n/a | self.write_file.flush() |
---|
4198 | n/a | |
---|
4199 | n/a | def testMakefileClose(self): |
---|
4200 | n/a | # The file returned by makefile should keep the socket open... |
---|
4201 | n/a | self.cli_conn.close() |
---|
4202 | n/a | msg = self.cli_conn.recv(1024) |
---|
4203 | n/a | self.assertEqual(msg, self.read_msg) |
---|
4204 | n/a | # ...until the file is itself closed |
---|
4205 | n/a | self.read_file.close() |
---|
4206 | n/a | self.assertRaises(OSError, self.cli_conn.recv, 1024) |
---|
4207 | n/a | |
---|
4208 | n/a | def _testMakefileClose(self): |
---|
4209 | n/a | self.write_file.write(self.write_msg) |
---|
4210 | n/a | self.write_file.flush() |
---|
4211 | n/a | |
---|
4212 | n/a | def testMakefileCloseSocketDestroy(self): |
---|
4213 | n/a | refcount_before = sys.getrefcount(self.cli_conn) |
---|
4214 | n/a | self.read_file.close() |
---|
4215 | n/a | refcount_after = sys.getrefcount(self.cli_conn) |
---|
4216 | n/a | self.assertEqual(refcount_before - 1, refcount_after) |
---|
4217 | n/a | |
---|
4218 | n/a | def _testMakefileCloseSocketDestroy(self): |
---|
4219 | n/a | pass |
---|
4220 | n/a | |
---|
4221 | n/a | # Non-blocking ops |
---|
4222 | n/a | # NOTE: to set `read_file` as non-blocking, we must call |
---|
4223 | n/a | # `cli_conn.setblocking` and vice-versa (see setUp / clientSetUp). |
---|
4224 | n/a | |
---|
4225 | n/a | def testSmallReadNonBlocking(self): |
---|
4226 | n/a | self.cli_conn.setblocking(False) |
---|
4227 | n/a | self.assertEqual(self.read_file.readinto(bytearray(10)), None) |
---|
4228 | n/a | self.assertEqual(self.read_file.read(len(self.read_msg) - 3), None) |
---|
4229 | n/a | self.evt1.set() |
---|
4230 | n/a | self.evt2.wait(1.0) |
---|
4231 | n/a | first_seg = self.read_file.read(len(self.read_msg) - 3) |
---|
4232 | n/a | if first_seg is None: |
---|
4233 | n/a | # Data not arrived (can happen under Windows), wait a bit |
---|
4234 | n/a | time.sleep(0.5) |
---|
4235 | n/a | first_seg = self.read_file.read(len(self.read_msg) - 3) |
---|
4236 | n/a | buf = bytearray(10) |
---|
4237 | n/a | n = self.read_file.readinto(buf) |
---|
4238 | n/a | self.assertEqual(n, 3) |
---|
4239 | n/a | msg = first_seg + buf[:n] |
---|
4240 | n/a | self.assertEqual(msg, self.read_msg) |
---|
4241 | n/a | self.assertEqual(self.read_file.readinto(bytearray(16)), None) |
---|
4242 | n/a | self.assertEqual(self.read_file.read(1), None) |
---|
4243 | n/a | |
---|
4244 | n/a | def _testSmallReadNonBlocking(self): |
---|
4245 | n/a | self.evt1.wait(1.0) |
---|
4246 | n/a | self.write_file.write(self.write_msg) |
---|
4247 | n/a | self.write_file.flush() |
---|
4248 | n/a | self.evt2.set() |
---|
4249 | n/a | # Avoid cloding the socket before the server test has finished, |
---|
4250 | n/a | # otherwise system recv() will return 0 instead of EWOULDBLOCK. |
---|
4251 | n/a | self.serv_finished.wait(5.0) |
---|
4252 | n/a | |
---|
4253 | n/a | def testWriteNonBlocking(self): |
---|
4254 | n/a | self.cli_finished.wait(5.0) |
---|
4255 | n/a | # The client thread can't skip directly - the SkipTest exception |
---|
4256 | n/a | # would appear as a failure. |
---|
4257 | n/a | if self.serv_skipped: |
---|
4258 | n/a | self.skipTest(self.serv_skipped) |
---|
4259 | n/a | |
---|
4260 | n/a | def _testWriteNonBlocking(self): |
---|
4261 | n/a | self.serv_skipped = None |
---|
4262 | n/a | self.serv_conn.setblocking(False) |
---|
4263 | n/a | # Try to saturate the socket buffer pipe with repeated large writes. |
---|
4264 | n/a | BIG = b"x" * support.SOCK_MAX_SIZE |
---|
4265 | n/a | LIMIT = 10 |
---|
4266 | n/a | # The first write() succeeds since a chunk of data can be buffered |
---|
4267 | n/a | n = self.write_file.write(BIG) |
---|
4268 | n/a | self.assertGreater(n, 0) |
---|
4269 | n/a | for i in range(LIMIT): |
---|
4270 | n/a | n = self.write_file.write(BIG) |
---|
4271 | n/a | if n is None: |
---|
4272 | n/a | # Succeeded |
---|
4273 | n/a | break |
---|
4274 | n/a | self.assertGreater(n, 0) |
---|
4275 | n/a | else: |
---|
4276 | n/a | # Let us know that this test didn't manage to establish |
---|
4277 | n/a | # the expected conditions. This is not a failure in itself but, |
---|
4278 | n/a | # if it happens repeatedly, the test should be fixed. |
---|
4279 | n/a | self.serv_skipped = "failed to saturate the socket buffer" |
---|
4280 | n/a | |
---|
4281 | n/a | |
---|
4282 | n/a | class LineBufferedFileObjectClassTestCase(FileObjectClassTestCase): |
---|
4283 | n/a | |
---|
4284 | n/a | bufsize = 1 # Default-buffered for reading; line-buffered for writing |
---|
4285 | n/a | |
---|
4286 | n/a | |
---|
4287 | n/a | class SmallBufferedFileObjectClassTestCase(FileObjectClassTestCase): |
---|
4288 | n/a | |
---|
4289 | n/a | bufsize = 2 # Exercise the buffering code |
---|
4290 | n/a | |
---|
4291 | n/a | |
---|
4292 | n/a | class UnicodeReadFileObjectClassTestCase(FileObjectClassTestCase): |
---|
4293 | n/a | """Tests for socket.makefile() in text mode (rather than binary)""" |
---|
4294 | n/a | |
---|
4295 | n/a | read_mode = 'r' |
---|
4296 | n/a | read_msg = MSG.decode('utf-8') |
---|
4297 | n/a | write_mode = 'wb' |
---|
4298 | n/a | write_msg = MSG |
---|
4299 | n/a | newline = '' |
---|
4300 | n/a | |
---|
4301 | n/a | |
---|
4302 | n/a | class UnicodeWriteFileObjectClassTestCase(FileObjectClassTestCase): |
---|
4303 | n/a | """Tests for socket.makefile() in text mode (rather than binary)""" |
---|
4304 | n/a | |
---|
4305 | n/a | read_mode = 'rb' |
---|
4306 | n/a | read_msg = MSG |
---|
4307 | n/a | write_mode = 'w' |
---|
4308 | n/a | write_msg = MSG.decode('utf-8') |
---|
4309 | n/a | newline = '' |
---|
4310 | n/a | |
---|
4311 | n/a | |
---|
4312 | n/a | class UnicodeReadWriteFileObjectClassTestCase(FileObjectClassTestCase): |
---|
4313 | n/a | """Tests for socket.makefile() in text mode (rather than binary)""" |
---|
4314 | n/a | |
---|
4315 | n/a | read_mode = 'r' |
---|
4316 | n/a | read_msg = MSG.decode('utf-8') |
---|
4317 | n/a | write_mode = 'w' |
---|
4318 | n/a | write_msg = MSG.decode('utf-8') |
---|
4319 | n/a | newline = '' |
---|
4320 | n/a | |
---|
4321 | n/a | |
---|
4322 | n/a | class NetworkConnectionTest(object): |
---|
4323 | n/a | """Prove network connection.""" |
---|
4324 | n/a | |
---|
4325 | n/a | def clientSetUp(self): |
---|
4326 | n/a | # We're inherited below by BasicTCPTest2, which also inherits |
---|
4327 | n/a | # BasicTCPTest, which defines self.port referenced below. |
---|
4328 | n/a | self.cli = socket.create_connection((HOST, self.port)) |
---|
4329 | n/a | self.serv_conn = self.cli |
---|
4330 | n/a | |
---|
4331 | n/a | class BasicTCPTest2(NetworkConnectionTest, BasicTCPTest): |
---|
4332 | n/a | """Tests that NetworkConnection does not break existing TCP functionality. |
---|
4333 | n/a | """ |
---|
4334 | n/a | |
---|
4335 | n/a | class NetworkConnectionNoServer(unittest.TestCase): |
---|
4336 | n/a | |
---|
4337 | n/a | class MockSocket(socket.socket): |
---|
4338 | n/a | def connect(self, *args): |
---|
4339 | n/a | raise socket.timeout('timed out') |
---|
4340 | n/a | |
---|
4341 | n/a | @contextlib.contextmanager |
---|
4342 | n/a | def mocked_socket_module(self): |
---|
4343 | n/a | """Return a socket which times out on connect""" |
---|
4344 | n/a | old_socket = socket.socket |
---|
4345 | n/a | socket.socket = self.MockSocket |
---|
4346 | n/a | try: |
---|
4347 | n/a | yield |
---|
4348 | n/a | finally: |
---|
4349 | n/a | socket.socket = old_socket |
---|
4350 | n/a | |
---|
4351 | n/a | def test_connect(self): |
---|
4352 | n/a | port = support.find_unused_port() |
---|
4353 | n/a | cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
---|
4354 | n/a | self.addCleanup(cli.close) |
---|
4355 | n/a | with self.assertRaises(OSError) as cm: |
---|
4356 | n/a | cli.connect((HOST, port)) |
---|
4357 | n/a | self.assertEqual(cm.exception.errno, errno.ECONNREFUSED) |
---|
4358 | n/a | |
---|
4359 | n/a | def test_create_connection(self): |
---|
4360 | n/a | # Issue #9792: errors raised by create_connection() should have |
---|
4361 | n/a | # a proper errno attribute. |
---|
4362 | n/a | port = support.find_unused_port() |
---|
4363 | n/a | with self.assertRaises(OSError) as cm: |
---|
4364 | n/a | socket.create_connection((HOST, port)) |
---|
4365 | n/a | |
---|
4366 | n/a | # Issue #16257: create_connection() calls getaddrinfo() against |
---|
4367 | n/a | # 'localhost'. This may result in an IPV6 addr being returned |
---|
4368 | n/a | # as well as an IPV4 one: |
---|
4369 | n/a | # >>> socket.getaddrinfo('localhost', port, 0, SOCK_STREAM) |
---|
4370 | n/a | # >>> [(2, 2, 0, '', ('127.0.0.1', 41230)), |
---|
4371 | n/a | # (26, 2, 0, '', ('::1', 41230, 0, 0))] |
---|
4372 | n/a | # |
---|
4373 | n/a | # create_connection() enumerates through all the addresses returned |
---|
4374 | n/a | # and if it doesn't successfully bind to any of them, it propagates |
---|
4375 | n/a | # the last exception it encountered. |
---|
4376 | n/a | # |
---|
4377 | n/a | # On Solaris, ENETUNREACH is returned in this circumstance instead |
---|
4378 | n/a | # of ECONNREFUSED. So, if that errno exists, add it to our list of |
---|
4379 | n/a | # expected errnos. |
---|
4380 | n/a | expected_errnos = [ errno.ECONNREFUSED, ] |
---|
4381 | n/a | if hasattr(errno, 'ENETUNREACH'): |
---|
4382 | n/a | expected_errnos.append(errno.ENETUNREACH) |
---|
4383 | n/a | |
---|
4384 | n/a | self.assertIn(cm.exception.errno, expected_errnos) |
---|
4385 | n/a | |
---|
4386 | n/a | def test_create_connection_timeout(self): |
---|
4387 | n/a | # Issue #9792: create_connection() should not recast timeout errors |
---|
4388 | n/a | # as generic socket errors. |
---|
4389 | n/a | with self.mocked_socket_module(): |
---|
4390 | n/a | with self.assertRaises(socket.timeout): |
---|
4391 | n/a | socket.create_connection((HOST, 1234)) |
---|
4392 | n/a | |
---|
4393 | n/a | |
---|
4394 | n/a | @unittest.skipUnless(thread, 'Threading required for this test.') |
---|
4395 | n/a | class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest): |
---|
4396 | n/a | |
---|
4397 | n/a | def __init__(self, methodName='runTest'): |
---|
4398 | n/a | SocketTCPTest.__init__(self, methodName=methodName) |
---|
4399 | n/a | ThreadableTest.__init__(self) |
---|
4400 | n/a | |
---|
4401 | n/a | def clientSetUp(self): |
---|
4402 | n/a | self.source_port = support.find_unused_port() |
---|
4403 | n/a | |
---|
4404 | n/a | def clientTearDown(self): |
---|
4405 | n/a | self.cli.close() |
---|
4406 | n/a | self.cli = None |
---|
4407 | n/a | ThreadableTest.clientTearDown(self) |
---|
4408 | n/a | |
---|
4409 | n/a | def _justAccept(self): |
---|
4410 | n/a | conn, addr = self.serv.accept() |
---|
4411 | n/a | conn.close() |
---|
4412 | n/a | |
---|
4413 | n/a | testFamily = _justAccept |
---|
4414 | n/a | def _testFamily(self): |
---|
4415 | n/a | self.cli = socket.create_connection((HOST, self.port), timeout=30) |
---|
4416 | n/a | self.addCleanup(self.cli.close) |
---|
4417 | n/a | self.assertEqual(self.cli.family, 2) |
---|
4418 | n/a | |
---|
4419 | n/a | testSourceAddress = _justAccept |
---|
4420 | n/a | def _testSourceAddress(self): |
---|
4421 | n/a | self.cli = socket.create_connection((HOST, self.port), timeout=30, |
---|
4422 | n/a | source_address=('', self.source_port)) |
---|
4423 | n/a | self.addCleanup(self.cli.close) |
---|
4424 | n/a | self.assertEqual(self.cli.getsockname()[1], self.source_port) |
---|
4425 | n/a | # The port number being used is sufficient to show that the bind() |
---|
4426 | n/a | # call happened. |
---|
4427 | n/a | |
---|
4428 | n/a | testTimeoutDefault = _justAccept |
---|
4429 | n/a | def _testTimeoutDefault(self): |
---|
4430 | n/a | # passing no explicit timeout uses socket's global default |
---|
4431 | n/a | self.assertTrue(socket.getdefaulttimeout() is None) |
---|
4432 | n/a | socket.setdefaulttimeout(42) |
---|
4433 | n/a | try: |
---|
4434 | n/a | self.cli = socket.create_connection((HOST, self.port)) |
---|
4435 | n/a | self.addCleanup(self.cli.close) |
---|
4436 | n/a | finally: |
---|
4437 | n/a | socket.setdefaulttimeout(None) |
---|
4438 | n/a | self.assertEqual(self.cli.gettimeout(), 42) |
---|
4439 | n/a | |
---|
4440 | n/a | testTimeoutNone = _justAccept |
---|
4441 | n/a | def _testTimeoutNone(self): |
---|
4442 | n/a | # None timeout means the same as sock.settimeout(None) |
---|
4443 | n/a | self.assertTrue(socket.getdefaulttimeout() is None) |
---|
4444 | n/a | socket.setdefaulttimeout(30) |
---|
4445 | n/a | try: |
---|
4446 | n/a | self.cli = socket.create_connection((HOST, self.port), timeout=None) |
---|
4447 | n/a | self.addCleanup(self.cli.close) |
---|
4448 | n/a | finally: |
---|
4449 | n/a | socket.setdefaulttimeout(None) |
---|
4450 | n/a | self.assertEqual(self.cli.gettimeout(), None) |
---|
4451 | n/a | |
---|
4452 | n/a | testTimeoutValueNamed = _justAccept |
---|
4453 | n/a | def _testTimeoutValueNamed(self): |
---|
4454 | n/a | self.cli = socket.create_connection((HOST, self.port), timeout=30) |
---|
4455 | n/a | self.assertEqual(self.cli.gettimeout(), 30) |
---|
4456 | n/a | |
---|
4457 | n/a | testTimeoutValueNonamed = _justAccept |
---|
4458 | n/a | def _testTimeoutValueNonamed(self): |
---|
4459 | n/a | self.cli = socket.create_connection((HOST, self.port), 30) |
---|
4460 | n/a | self.addCleanup(self.cli.close) |
---|
4461 | n/a | self.assertEqual(self.cli.gettimeout(), 30) |
---|
4462 | n/a | |
---|
4463 | n/a | @unittest.skipUnless(thread, 'Threading required for this test.') |
---|
4464 | n/a | class NetworkConnectionBehaviourTest(SocketTCPTest, ThreadableTest): |
---|
4465 | n/a | |
---|
4466 | n/a | def __init__(self, methodName='runTest'): |
---|
4467 | n/a | SocketTCPTest.__init__(self, methodName=methodName) |
---|
4468 | n/a | ThreadableTest.__init__(self) |
---|
4469 | n/a | |
---|
4470 | n/a | def clientSetUp(self): |
---|
4471 | n/a | pass |
---|
4472 | n/a | |
---|
4473 | n/a | def clientTearDown(self): |
---|
4474 | n/a | self.cli.close() |
---|
4475 | n/a | self.cli = None |
---|
4476 | n/a | ThreadableTest.clientTearDown(self) |
---|
4477 | n/a | |
---|
4478 | n/a | def testInsideTimeout(self): |
---|
4479 | n/a | conn, addr = self.serv.accept() |
---|
4480 | n/a | self.addCleanup(conn.close) |
---|
4481 | n/a | time.sleep(3) |
---|
4482 | n/a | conn.send(b"done!") |
---|
4483 | n/a | testOutsideTimeout = testInsideTimeout |
---|
4484 | n/a | |
---|
4485 | n/a | def _testInsideTimeout(self): |
---|
4486 | n/a | self.cli = sock = socket.create_connection((HOST, self.port)) |
---|
4487 | n/a | data = sock.recv(5) |
---|
4488 | n/a | self.assertEqual(data, b"done!") |
---|
4489 | n/a | |
---|
4490 | n/a | def _testOutsideTimeout(self): |
---|
4491 | n/a | self.cli = sock = socket.create_connection((HOST, self.port), timeout=1) |
---|
4492 | n/a | self.assertRaises(socket.timeout, lambda: sock.recv(5)) |
---|
4493 | n/a | |
---|
4494 | n/a | |
---|
4495 | n/a | class TCPTimeoutTest(SocketTCPTest): |
---|
4496 | n/a | |
---|
4497 | n/a | def testTCPTimeout(self): |
---|
4498 | n/a | def raise_timeout(*args, **kwargs): |
---|
4499 | n/a | self.serv.settimeout(1.0) |
---|
4500 | n/a | self.serv.accept() |
---|
4501 | n/a | self.assertRaises(socket.timeout, raise_timeout, |
---|
4502 | n/a | "Error generating a timeout exception (TCP)") |
---|
4503 | n/a | |
---|
4504 | n/a | def testTimeoutZero(self): |
---|
4505 | n/a | ok = False |
---|
4506 | n/a | try: |
---|
4507 | n/a | self.serv.settimeout(0.0) |
---|
4508 | n/a | foo = self.serv.accept() |
---|
4509 | n/a | except socket.timeout: |
---|
4510 | n/a | self.fail("caught timeout instead of error (TCP)") |
---|
4511 | n/a | except OSError: |
---|
4512 | n/a | ok = True |
---|
4513 | n/a | except: |
---|
4514 | n/a | self.fail("caught unexpected exception (TCP)") |
---|
4515 | n/a | if not ok: |
---|
4516 | n/a | self.fail("accept() returned success when we did not expect it") |
---|
4517 | n/a | |
---|
4518 | n/a | @unittest.skipUnless(hasattr(signal, 'alarm'), |
---|
4519 | n/a | 'test needs signal.alarm()') |
---|
4520 | n/a | def testInterruptedTimeout(self): |
---|
4521 | n/a | # XXX I don't know how to do this test on MSWindows or any other |
---|
4522 | n/a | # plaform that doesn't support signal.alarm() or os.kill(), though |
---|
4523 | n/a | # the bug should have existed on all platforms. |
---|
4524 | n/a | self.serv.settimeout(5.0) # must be longer than alarm |
---|
4525 | n/a | class Alarm(Exception): |
---|
4526 | n/a | pass |
---|
4527 | n/a | def alarm_handler(signal, frame): |
---|
4528 | n/a | raise Alarm |
---|
4529 | n/a | old_alarm = signal.signal(signal.SIGALRM, alarm_handler) |
---|
4530 | n/a | try: |
---|
4531 | n/a | signal.alarm(2) # POSIX allows alarm to be up to 1 second early |
---|
4532 | n/a | try: |
---|
4533 | n/a | foo = self.serv.accept() |
---|
4534 | n/a | except socket.timeout: |
---|
4535 | n/a | self.fail("caught timeout instead of Alarm") |
---|
4536 | n/a | except Alarm: |
---|
4537 | n/a | pass |
---|
4538 | n/a | except: |
---|
4539 | n/a | self.fail("caught other exception instead of Alarm:" |
---|
4540 | n/a | " %s(%s):\n%s" % |
---|
4541 | n/a | (sys.exc_info()[:2] + (traceback.format_exc(),))) |
---|
4542 | n/a | else: |
---|
4543 | n/a | self.fail("nothing caught") |
---|
4544 | n/a | finally: |
---|
4545 | n/a | signal.alarm(0) # shut off alarm |
---|
4546 | n/a | except Alarm: |
---|
4547 | n/a | self.fail("got Alarm in wrong place") |
---|
4548 | n/a | finally: |
---|
4549 | n/a | # no alarm can be pending. Safe to restore old handler. |
---|
4550 | n/a | signal.signal(signal.SIGALRM, old_alarm) |
---|
4551 | n/a | |
---|
4552 | n/a | class UDPTimeoutTest(SocketUDPTest): |
---|
4553 | n/a | |
---|
4554 | n/a | def testUDPTimeout(self): |
---|
4555 | n/a | def raise_timeout(*args, **kwargs): |
---|
4556 | n/a | self.serv.settimeout(1.0) |
---|
4557 | n/a | self.serv.recv(1024) |
---|
4558 | n/a | self.assertRaises(socket.timeout, raise_timeout, |
---|
4559 | n/a | "Error generating a timeout exception (UDP)") |
---|
4560 | n/a | |
---|
4561 | n/a | def testTimeoutZero(self): |
---|
4562 | n/a | ok = False |
---|
4563 | n/a | try: |
---|
4564 | n/a | self.serv.settimeout(0.0) |
---|
4565 | n/a | foo = self.serv.recv(1024) |
---|
4566 | n/a | except socket.timeout: |
---|
4567 | n/a | self.fail("caught timeout instead of error (UDP)") |
---|
4568 | n/a | except OSError: |
---|
4569 | n/a | ok = True |
---|
4570 | n/a | except: |
---|
4571 | n/a | self.fail("caught unexpected exception (UDP)") |
---|
4572 | n/a | if not ok: |
---|
4573 | n/a | self.fail("recv() returned success when we did not expect it") |
---|
4574 | n/a | |
---|
4575 | n/a | class TestExceptions(unittest.TestCase): |
---|
4576 | n/a | |
---|
4577 | n/a | def testExceptionTree(self): |
---|
4578 | n/a | self.assertTrue(issubclass(OSError, Exception)) |
---|
4579 | n/a | self.assertTrue(issubclass(socket.herror, OSError)) |
---|
4580 | n/a | self.assertTrue(issubclass(socket.gaierror, OSError)) |
---|
4581 | n/a | self.assertTrue(issubclass(socket.timeout, OSError)) |
---|
4582 | n/a | |
---|
4583 | n/a | def test_setblocking_invalidfd(self): |
---|
4584 | n/a | # Regression test for issue #28471 |
---|
4585 | n/a | |
---|
4586 | n/a | sock0 = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) |
---|
4587 | n/a | sock = socket.socket( |
---|
4588 | n/a | socket.AF_INET, socket.SOCK_STREAM, 0, sock0.fileno()) |
---|
4589 | n/a | sock0.close() |
---|
4590 | n/a | self.addCleanup(sock.detach) |
---|
4591 | n/a | |
---|
4592 | n/a | with self.assertRaises(OSError): |
---|
4593 | n/a | sock.setblocking(False) |
---|
4594 | n/a | |
---|
4595 | n/a | |
---|
4596 | n/a | @unittest.skipUnless(sys.platform == 'linux', 'Linux specific test') |
---|
4597 | n/a | class TestLinuxAbstractNamespace(unittest.TestCase): |
---|
4598 | n/a | |
---|
4599 | n/a | UNIX_PATH_MAX = 108 |
---|
4600 | n/a | |
---|
4601 | n/a | def testLinuxAbstractNamespace(self): |
---|
4602 | n/a | address = b"\x00python-test-hello\x00\xff" |
---|
4603 | n/a | with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s1: |
---|
4604 | n/a | s1.bind(address) |
---|
4605 | n/a | s1.listen() |
---|
4606 | n/a | with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s2: |
---|
4607 | n/a | s2.connect(s1.getsockname()) |
---|
4608 | n/a | with s1.accept()[0] as s3: |
---|
4609 | n/a | self.assertEqual(s1.getsockname(), address) |
---|
4610 | n/a | self.assertEqual(s2.getpeername(), address) |
---|
4611 | n/a | |
---|
4612 | n/a | def testMaxName(self): |
---|
4613 | n/a | address = b"\x00" + b"h" * (self.UNIX_PATH_MAX - 1) |
---|
4614 | n/a | with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s: |
---|
4615 | n/a | s.bind(address) |
---|
4616 | n/a | self.assertEqual(s.getsockname(), address) |
---|
4617 | n/a | |
---|
4618 | n/a | def testNameOverflow(self): |
---|
4619 | n/a | address = "\x00" + "h" * self.UNIX_PATH_MAX |
---|
4620 | n/a | with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s: |
---|
4621 | n/a | self.assertRaises(OSError, s.bind, address) |
---|
4622 | n/a | |
---|
4623 | n/a | def testStrName(self): |
---|
4624 | n/a | # Check that an abstract name can be passed as a string. |
---|
4625 | n/a | s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
---|
4626 | n/a | try: |
---|
4627 | n/a | s.bind("\x00python\x00test\x00") |
---|
4628 | n/a | self.assertEqual(s.getsockname(), b"\x00python\x00test\x00") |
---|
4629 | n/a | finally: |
---|
4630 | n/a | s.close() |
---|
4631 | n/a | |
---|
4632 | n/a | def testBytearrayName(self): |
---|
4633 | n/a | # Check that an abstract name can be passed as a bytearray. |
---|
4634 | n/a | with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s: |
---|
4635 | n/a | s.bind(bytearray(b"\x00python\x00test\x00")) |
---|
4636 | n/a | self.assertEqual(s.getsockname(), b"\x00python\x00test\x00") |
---|
4637 | n/a | |
---|
4638 | n/a | @unittest.skipUnless(hasattr(socket, 'AF_UNIX'), 'test needs socket.AF_UNIX') |
---|
4639 | n/a | class TestUnixDomain(unittest.TestCase): |
---|
4640 | n/a | |
---|
4641 | n/a | def setUp(self): |
---|
4642 | n/a | self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
---|
4643 | n/a | |
---|
4644 | n/a | def tearDown(self): |
---|
4645 | n/a | self.sock.close() |
---|
4646 | n/a | |
---|
4647 | n/a | def encoded(self, path): |
---|
4648 | n/a | # Return the given path encoded in the file system encoding, |
---|
4649 | n/a | # or skip the test if this is not possible. |
---|
4650 | n/a | try: |
---|
4651 | n/a | return os.fsencode(path) |
---|
4652 | n/a | except UnicodeEncodeError: |
---|
4653 | n/a | self.skipTest( |
---|
4654 | n/a | "Pathname {0!a} cannot be represented in file " |
---|
4655 | n/a | "system encoding {1!r}".format( |
---|
4656 | n/a | path, sys.getfilesystemencoding())) |
---|
4657 | n/a | |
---|
4658 | n/a | def bind(self, sock, path): |
---|
4659 | n/a | # Bind the socket |
---|
4660 | n/a | try: |
---|
4661 | n/a | support.bind_unix_socket(sock, path) |
---|
4662 | n/a | except OSError as e: |
---|
4663 | n/a | if str(e) == "AF_UNIX path too long": |
---|
4664 | n/a | self.skipTest( |
---|
4665 | n/a | "Pathname {0!a} is too long to serve as an AF_UNIX path" |
---|
4666 | n/a | .format(path)) |
---|
4667 | n/a | else: |
---|
4668 | n/a | raise |
---|
4669 | n/a | |
---|
4670 | n/a | def testStrAddr(self): |
---|
4671 | n/a | # Test binding to and retrieving a normal string pathname. |
---|
4672 | n/a | path = os.path.abspath(support.TESTFN) |
---|
4673 | n/a | self.bind(self.sock, path) |
---|
4674 | n/a | self.addCleanup(support.unlink, path) |
---|
4675 | n/a | self.assertEqual(self.sock.getsockname(), path) |
---|
4676 | n/a | |
---|
4677 | n/a | def testBytesAddr(self): |
---|
4678 | n/a | # Test binding to a bytes pathname. |
---|
4679 | n/a | path = os.path.abspath(support.TESTFN) |
---|
4680 | n/a | self.bind(self.sock, self.encoded(path)) |
---|
4681 | n/a | self.addCleanup(support.unlink, path) |
---|
4682 | n/a | self.assertEqual(self.sock.getsockname(), path) |
---|
4683 | n/a | |
---|
4684 | n/a | def testSurrogateescapeBind(self): |
---|
4685 | n/a | # Test binding to a valid non-ASCII pathname, with the |
---|
4686 | n/a | # non-ASCII bytes supplied using surrogateescape encoding. |
---|
4687 | n/a | path = os.path.abspath(support.TESTFN_UNICODE) |
---|
4688 | n/a | b = self.encoded(path) |
---|
4689 | n/a | self.bind(self.sock, b.decode("ascii", "surrogateescape")) |
---|
4690 | n/a | self.addCleanup(support.unlink, path) |
---|
4691 | n/a | self.assertEqual(self.sock.getsockname(), path) |
---|
4692 | n/a | |
---|
4693 | n/a | def testUnencodableAddr(self): |
---|
4694 | n/a | # Test binding to a pathname that cannot be encoded in the |
---|
4695 | n/a | # file system encoding. |
---|
4696 | n/a | if support.TESTFN_UNENCODABLE is None: |
---|
4697 | n/a | self.skipTest("No unencodable filename available") |
---|
4698 | n/a | path = os.path.abspath(support.TESTFN_UNENCODABLE) |
---|
4699 | n/a | self.bind(self.sock, path) |
---|
4700 | n/a | self.addCleanup(support.unlink, path) |
---|
4701 | n/a | self.assertEqual(self.sock.getsockname(), path) |
---|
4702 | n/a | |
---|
4703 | n/a | @unittest.skipUnless(thread, 'Threading required for this test.') |
---|
4704 | n/a | class BufferIOTest(SocketConnectedTest): |
---|
4705 | n/a | """ |
---|
4706 | n/a | Test the buffer versions of socket.recv() and socket.send(). |
---|
4707 | n/a | """ |
---|
4708 | n/a | def __init__(self, methodName='runTest'): |
---|
4709 | n/a | SocketConnectedTest.__init__(self, methodName=methodName) |
---|
4710 | n/a | |
---|
4711 | n/a | def testRecvIntoArray(self): |
---|
4712 | n/a | buf = array.array("B", [0] * len(MSG)) |
---|
4713 | n/a | nbytes = self.cli_conn.recv_into(buf) |
---|
4714 | n/a | self.assertEqual(nbytes, len(MSG)) |
---|
4715 | n/a | buf = buf.tobytes() |
---|
4716 | n/a | msg = buf[:len(MSG)] |
---|
4717 | n/a | self.assertEqual(msg, MSG) |
---|
4718 | n/a | |
---|
4719 | n/a | def _testRecvIntoArray(self): |
---|
4720 | n/a | buf = bytes(MSG) |
---|
4721 | n/a | self.serv_conn.send(buf) |
---|
4722 | n/a | |
---|
4723 | n/a | def testRecvIntoBytearray(self): |
---|
4724 | n/a | buf = bytearray(1024) |
---|
4725 | n/a | nbytes = self.cli_conn.recv_into(buf) |
---|
4726 | n/a | self.assertEqual(nbytes, len(MSG)) |
---|
4727 | n/a | msg = buf[:len(MSG)] |
---|
4728 | n/a | self.assertEqual(msg, MSG) |
---|
4729 | n/a | |
---|
4730 | n/a | _testRecvIntoBytearray = _testRecvIntoArray |
---|
4731 | n/a | |
---|
4732 | n/a | def testRecvIntoMemoryview(self): |
---|
4733 | n/a | buf = bytearray(1024) |
---|
4734 | n/a | nbytes = self.cli_conn.recv_into(memoryview(buf)) |
---|
4735 | n/a | self.assertEqual(nbytes, len(MSG)) |
---|
4736 | n/a | msg = buf[:len(MSG)] |
---|
4737 | n/a | self.assertEqual(msg, MSG) |
---|
4738 | n/a | |
---|
4739 | n/a | _testRecvIntoMemoryview = _testRecvIntoArray |
---|
4740 | n/a | |
---|
4741 | n/a | def testRecvFromIntoArray(self): |
---|
4742 | n/a | buf = array.array("B", [0] * len(MSG)) |
---|
4743 | n/a | nbytes, addr = self.cli_conn.recvfrom_into(buf) |
---|
4744 | n/a | self.assertEqual(nbytes, len(MSG)) |
---|
4745 | n/a | buf = buf.tobytes() |
---|
4746 | n/a | msg = buf[:len(MSG)] |
---|
4747 | n/a | self.assertEqual(msg, MSG) |
---|
4748 | n/a | |
---|
4749 | n/a | def _testRecvFromIntoArray(self): |
---|
4750 | n/a | buf = bytes(MSG) |
---|
4751 | n/a | self.serv_conn.send(buf) |
---|
4752 | n/a | |
---|
4753 | n/a | def testRecvFromIntoBytearray(self): |
---|
4754 | n/a | buf = bytearray(1024) |
---|
4755 | n/a | nbytes, addr = self.cli_conn.recvfrom_into(buf) |
---|
4756 | n/a | self.assertEqual(nbytes, len(MSG)) |
---|
4757 | n/a | msg = buf[:len(MSG)] |
---|
4758 | n/a | self.assertEqual(msg, MSG) |
---|
4759 | n/a | |
---|
4760 | n/a | _testRecvFromIntoBytearray = _testRecvFromIntoArray |
---|
4761 | n/a | |
---|
4762 | n/a | def testRecvFromIntoMemoryview(self): |
---|
4763 | n/a | buf = bytearray(1024) |
---|
4764 | n/a | nbytes, addr = self.cli_conn.recvfrom_into(memoryview(buf)) |
---|
4765 | n/a | self.assertEqual(nbytes, len(MSG)) |
---|
4766 | n/a | msg = buf[:len(MSG)] |
---|
4767 | n/a | self.assertEqual(msg, MSG) |
---|
4768 | n/a | |
---|
4769 | n/a | _testRecvFromIntoMemoryview = _testRecvFromIntoArray |
---|
4770 | n/a | |
---|
4771 | n/a | def testRecvFromIntoSmallBuffer(self): |
---|
4772 | n/a | # See issue #20246. |
---|
4773 | n/a | buf = bytearray(8) |
---|
4774 | n/a | self.assertRaises(ValueError, self.cli_conn.recvfrom_into, buf, 1024) |
---|
4775 | n/a | |
---|
4776 | n/a | def _testRecvFromIntoSmallBuffer(self): |
---|
4777 | n/a | self.serv_conn.send(MSG) |
---|
4778 | n/a | |
---|
4779 | n/a | def testRecvFromIntoEmptyBuffer(self): |
---|
4780 | n/a | buf = bytearray() |
---|
4781 | n/a | self.cli_conn.recvfrom_into(buf) |
---|
4782 | n/a | self.cli_conn.recvfrom_into(buf, 0) |
---|
4783 | n/a | |
---|
4784 | n/a | _testRecvFromIntoEmptyBuffer = _testRecvFromIntoArray |
---|
4785 | n/a | |
---|
4786 | n/a | |
---|
4787 | n/a | TIPC_STYPE = 2000 |
---|
4788 | n/a | TIPC_LOWER = 200 |
---|
4789 | n/a | TIPC_UPPER = 210 |
---|
4790 | n/a | |
---|
4791 | n/a | def isTipcAvailable(): |
---|
4792 | n/a | """Check if the TIPC module is loaded |
---|
4793 | n/a | |
---|
4794 | n/a | The TIPC module is not loaded automatically on Ubuntu and probably |
---|
4795 | n/a | other Linux distros. |
---|
4796 | n/a | """ |
---|
4797 | n/a | if not hasattr(socket, "AF_TIPC"): |
---|
4798 | n/a | return False |
---|
4799 | n/a | try: |
---|
4800 | n/a | f = open("/proc/modules") |
---|
4801 | n/a | except (FileNotFoundError, IsADirectoryError, PermissionError): |
---|
4802 | n/a | # It's ok if the file does not exist, is a directory or if we |
---|
4803 | n/a | # have not the permission to read it. |
---|
4804 | n/a | return False |
---|
4805 | n/a | with f: |
---|
4806 | n/a | for line in f: |
---|
4807 | n/a | if line.startswith("tipc "): |
---|
4808 | n/a | return True |
---|
4809 | n/a | return False |
---|
4810 | n/a | |
---|
4811 | n/a | @unittest.skipUnless(isTipcAvailable(), |
---|
4812 | n/a | "TIPC module is not loaded, please 'sudo modprobe tipc'") |
---|
4813 | n/a | class TIPCTest(unittest.TestCase): |
---|
4814 | n/a | def testRDM(self): |
---|
4815 | n/a | srv = socket.socket(socket.AF_TIPC, socket.SOCK_RDM) |
---|
4816 | n/a | cli = socket.socket(socket.AF_TIPC, socket.SOCK_RDM) |
---|
4817 | n/a | self.addCleanup(srv.close) |
---|
4818 | n/a | self.addCleanup(cli.close) |
---|
4819 | n/a | |
---|
4820 | n/a | srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
---|
4821 | n/a | srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE, |
---|
4822 | n/a | TIPC_LOWER, TIPC_UPPER) |
---|
4823 | n/a | srv.bind(srvaddr) |
---|
4824 | n/a | |
---|
4825 | n/a | sendaddr = (socket.TIPC_ADDR_NAME, TIPC_STYPE, |
---|
4826 | n/a | TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0) |
---|
4827 | n/a | cli.sendto(MSG, sendaddr) |
---|
4828 | n/a | |
---|
4829 | n/a | msg, recvaddr = srv.recvfrom(1024) |
---|
4830 | n/a | |
---|
4831 | n/a | self.assertEqual(cli.getsockname(), recvaddr) |
---|
4832 | n/a | self.assertEqual(msg, MSG) |
---|
4833 | n/a | |
---|
4834 | n/a | |
---|
4835 | n/a | @unittest.skipUnless(isTipcAvailable(), |
---|
4836 | n/a | "TIPC module is not loaded, please 'sudo modprobe tipc'") |
---|
4837 | n/a | class TIPCThreadableTest(unittest.TestCase, ThreadableTest): |
---|
4838 | n/a | def __init__(self, methodName = 'runTest'): |
---|
4839 | n/a | unittest.TestCase.__init__(self, methodName = methodName) |
---|
4840 | n/a | ThreadableTest.__init__(self) |
---|
4841 | n/a | |
---|
4842 | n/a | def setUp(self): |
---|
4843 | n/a | self.srv = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM) |
---|
4844 | n/a | self.addCleanup(self.srv.close) |
---|
4845 | n/a | self.srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
---|
4846 | n/a | srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE, |
---|
4847 | n/a | TIPC_LOWER, TIPC_UPPER) |
---|
4848 | n/a | self.srv.bind(srvaddr) |
---|
4849 | n/a | self.srv.listen() |
---|
4850 | n/a | self.serverExplicitReady() |
---|
4851 | n/a | self.conn, self.connaddr = self.srv.accept() |
---|
4852 | n/a | self.addCleanup(self.conn.close) |
---|
4853 | n/a | |
---|
4854 | n/a | def clientSetUp(self): |
---|
4855 | n/a | # There is a hittable race between serverExplicitReady() and the |
---|
4856 | n/a | # accept() call; sleep a little while to avoid it, otherwise |
---|
4857 | n/a | # we could get an exception |
---|
4858 | n/a | time.sleep(0.1) |
---|
4859 | n/a | self.cli = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM) |
---|
4860 | n/a | self.addCleanup(self.cli.close) |
---|
4861 | n/a | addr = (socket.TIPC_ADDR_NAME, TIPC_STYPE, |
---|
4862 | n/a | TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0) |
---|
4863 | n/a | self.cli.connect(addr) |
---|
4864 | n/a | self.cliaddr = self.cli.getsockname() |
---|
4865 | n/a | |
---|
4866 | n/a | def testStream(self): |
---|
4867 | n/a | msg = self.conn.recv(1024) |
---|
4868 | n/a | self.assertEqual(msg, MSG) |
---|
4869 | n/a | self.assertEqual(self.cliaddr, self.connaddr) |
---|
4870 | n/a | |
---|
4871 | n/a | def _testStream(self): |
---|
4872 | n/a | self.cli.send(MSG) |
---|
4873 | n/a | self.cli.close() |
---|
4874 | n/a | |
---|
4875 | n/a | |
---|
4876 | n/a | @unittest.skipUnless(thread, 'Threading required for this test.') |
---|
4877 | n/a | class ContextManagersTest(ThreadedTCPSocketTest): |
---|
4878 | n/a | |
---|
4879 | n/a | def _testSocketClass(self): |
---|
4880 | n/a | # base test |
---|
4881 | n/a | with socket.socket() as sock: |
---|
4882 | n/a | self.assertFalse(sock._closed) |
---|
4883 | n/a | self.assertTrue(sock._closed) |
---|
4884 | n/a | # close inside with block |
---|
4885 | n/a | with socket.socket() as sock: |
---|
4886 | n/a | sock.close() |
---|
4887 | n/a | self.assertTrue(sock._closed) |
---|
4888 | n/a | # exception inside with block |
---|
4889 | n/a | with socket.socket() as sock: |
---|
4890 | n/a | self.assertRaises(OSError, sock.sendall, b'foo') |
---|
4891 | n/a | self.assertTrue(sock._closed) |
---|
4892 | n/a | |
---|
4893 | n/a | def testCreateConnectionBase(self): |
---|
4894 | n/a | conn, addr = self.serv.accept() |
---|
4895 | n/a | self.addCleanup(conn.close) |
---|
4896 | n/a | data = conn.recv(1024) |
---|
4897 | n/a | conn.sendall(data) |
---|
4898 | n/a | |
---|
4899 | n/a | def _testCreateConnectionBase(self): |
---|
4900 | n/a | address = self.serv.getsockname() |
---|
4901 | n/a | with socket.create_connection(address) as sock: |
---|
4902 | n/a | self.assertFalse(sock._closed) |
---|
4903 | n/a | sock.sendall(b'foo') |
---|
4904 | n/a | self.assertEqual(sock.recv(1024), b'foo') |
---|
4905 | n/a | self.assertTrue(sock._closed) |
---|
4906 | n/a | |
---|
4907 | n/a | def testCreateConnectionClose(self): |
---|
4908 | n/a | conn, addr = self.serv.accept() |
---|
4909 | n/a | self.addCleanup(conn.close) |
---|
4910 | n/a | data = conn.recv(1024) |
---|
4911 | n/a | conn.sendall(data) |
---|
4912 | n/a | |
---|
4913 | n/a | def _testCreateConnectionClose(self): |
---|
4914 | n/a | address = self.serv.getsockname() |
---|
4915 | n/a | with socket.create_connection(address) as sock: |
---|
4916 | n/a | sock.close() |
---|
4917 | n/a | self.assertTrue(sock._closed) |
---|
4918 | n/a | self.assertRaises(OSError, sock.sendall, b'foo') |
---|
4919 | n/a | |
---|
4920 | n/a | |
---|
4921 | n/a | class InheritanceTest(unittest.TestCase): |
---|
4922 | n/a | @unittest.skipUnless(hasattr(socket, "SOCK_CLOEXEC"), |
---|
4923 | n/a | "SOCK_CLOEXEC not defined") |
---|
4924 | n/a | @support.requires_linux_version(2, 6, 28) |
---|
4925 | n/a | def test_SOCK_CLOEXEC(self): |
---|
4926 | n/a | with socket.socket(socket.AF_INET, |
---|
4927 | n/a | socket.SOCK_STREAM | socket.SOCK_CLOEXEC) as s: |
---|
4928 | n/a | self.assertTrue(s.type & socket.SOCK_CLOEXEC) |
---|
4929 | n/a | self.assertFalse(s.get_inheritable()) |
---|
4930 | n/a | |
---|
4931 | n/a | def test_default_inheritable(self): |
---|
4932 | n/a | sock = socket.socket() |
---|
4933 | n/a | with sock: |
---|
4934 | n/a | self.assertEqual(sock.get_inheritable(), False) |
---|
4935 | n/a | |
---|
4936 | n/a | def test_dup(self): |
---|
4937 | n/a | sock = socket.socket() |
---|
4938 | n/a | with sock: |
---|
4939 | n/a | newsock = sock.dup() |
---|
4940 | n/a | sock.close() |
---|
4941 | n/a | with newsock: |
---|
4942 | n/a | self.assertEqual(newsock.get_inheritable(), False) |
---|
4943 | n/a | |
---|
4944 | n/a | def test_set_inheritable(self): |
---|
4945 | n/a | sock = socket.socket() |
---|
4946 | n/a | with sock: |
---|
4947 | n/a | sock.set_inheritable(True) |
---|
4948 | n/a | self.assertEqual(sock.get_inheritable(), True) |
---|
4949 | n/a | |
---|
4950 | n/a | sock.set_inheritable(False) |
---|
4951 | n/a | self.assertEqual(sock.get_inheritable(), False) |
---|
4952 | n/a | |
---|
4953 | n/a | @unittest.skipIf(fcntl is None, "need fcntl") |
---|
4954 | n/a | def test_get_inheritable_cloexec(self): |
---|
4955 | n/a | sock = socket.socket() |
---|
4956 | n/a | with sock: |
---|
4957 | n/a | fd = sock.fileno() |
---|
4958 | n/a | self.assertEqual(sock.get_inheritable(), False) |
---|
4959 | n/a | |
---|
4960 | n/a | # clear FD_CLOEXEC flag |
---|
4961 | n/a | flags = fcntl.fcntl(fd, fcntl.F_GETFD) |
---|
4962 | n/a | flags &= ~fcntl.FD_CLOEXEC |
---|
4963 | n/a | fcntl.fcntl(fd, fcntl.F_SETFD, flags) |
---|
4964 | n/a | |
---|
4965 | n/a | self.assertEqual(sock.get_inheritable(), True) |
---|
4966 | n/a | |
---|
4967 | n/a | @unittest.skipIf(fcntl is None, "need fcntl") |
---|
4968 | n/a | def test_set_inheritable_cloexec(self): |
---|
4969 | n/a | sock = socket.socket() |
---|
4970 | n/a | with sock: |
---|
4971 | n/a | fd = sock.fileno() |
---|
4972 | n/a | self.assertEqual(fcntl.fcntl(fd, fcntl.F_GETFD) & fcntl.FD_CLOEXEC, |
---|
4973 | n/a | fcntl.FD_CLOEXEC) |
---|
4974 | n/a | |
---|
4975 | n/a | sock.set_inheritable(True) |
---|
4976 | n/a | self.assertEqual(fcntl.fcntl(fd, fcntl.F_GETFD) & fcntl.FD_CLOEXEC, |
---|
4977 | n/a | 0) |
---|
4978 | n/a | |
---|
4979 | n/a | |
---|
4980 | n/a | @unittest.skipUnless(hasattr(socket, "socketpair"), |
---|
4981 | n/a | "need socket.socketpair()") |
---|
4982 | n/a | def test_socketpair(self): |
---|
4983 | n/a | s1, s2 = socket.socketpair() |
---|
4984 | n/a | self.addCleanup(s1.close) |
---|
4985 | n/a | self.addCleanup(s2.close) |
---|
4986 | n/a | self.assertEqual(s1.get_inheritable(), False) |
---|
4987 | n/a | self.assertEqual(s2.get_inheritable(), False) |
---|
4988 | n/a | |
---|
4989 | n/a | |
---|
4990 | n/a | @unittest.skipUnless(hasattr(socket, "SOCK_NONBLOCK"), |
---|
4991 | n/a | "SOCK_NONBLOCK not defined") |
---|
4992 | n/a | class NonblockConstantTest(unittest.TestCase): |
---|
4993 | n/a | def checkNonblock(self, s, nonblock=True, timeout=0.0): |
---|
4994 | n/a | if nonblock: |
---|
4995 | n/a | self.assertTrue(s.type & socket.SOCK_NONBLOCK) |
---|
4996 | n/a | self.assertEqual(s.gettimeout(), timeout) |
---|
4997 | n/a | else: |
---|
4998 | n/a | self.assertFalse(s.type & socket.SOCK_NONBLOCK) |
---|
4999 | n/a | self.assertEqual(s.gettimeout(), None) |
---|
5000 | n/a | |
---|
5001 | n/a | @support.requires_linux_version(2, 6, 28) |
---|
5002 | n/a | def test_SOCK_NONBLOCK(self): |
---|
5003 | n/a | # a lot of it seems silly and redundant, but I wanted to test that |
---|
5004 | n/a | # changing back and forth worked ok |
---|
5005 | n/a | with socket.socket(socket.AF_INET, |
---|
5006 | n/a | socket.SOCK_STREAM | socket.SOCK_NONBLOCK) as s: |
---|
5007 | n/a | self.checkNonblock(s) |
---|
5008 | n/a | s.setblocking(1) |
---|
5009 | n/a | self.checkNonblock(s, False) |
---|
5010 | n/a | s.setblocking(0) |
---|
5011 | n/a | self.checkNonblock(s) |
---|
5012 | n/a | s.settimeout(None) |
---|
5013 | n/a | self.checkNonblock(s, False) |
---|
5014 | n/a | s.settimeout(2.0) |
---|
5015 | n/a | self.checkNonblock(s, timeout=2.0) |
---|
5016 | n/a | s.setblocking(1) |
---|
5017 | n/a | self.checkNonblock(s, False) |
---|
5018 | n/a | # defaulttimeout |
---|
5019 | n/a | t = socket.getdefaulttimeout() |
---|
5020 | n/a | socket.setdefaulttimeout(0.0) |
---|
5021 | n/a | with socket.socket() as s: |
---|
5022 | n/a | self.checkNonblock(s) |
---|
5023 | n/a | socket.setdefaulttimeout(None) |
---|
5024 | n/a | with socket.socket() as s: |
---|
5025 | n/a | self.checkNonblock(s, False) |
---|
5026 | n/a | socket.setdefaulttimeout(2.0) |
---|
5027 | n/a | with socket.socket() as s: |
---|
5028 | n/a | self.checkNonblock(s, timeout=2.0) |
---|
5029 | n/a | socket.setdefaulttimeout(None) |
---|
5030 | n/a | with socket.socket() as s: |
---|
5031 | n/a | self.checkNonblock(s, False) |
---|
5032 | n/a | socket.setdefaulttimeout(t) |
---|
5033 | n/a | |
---|
5034 | n/a | |
---|
5035 | n/a | @unittest.skipUnless(os.name == "nt", "Windows specific") |
---|
5036 | n/a | @unittest.skipUnless(multiprocessing, "need multiprocessing") |
---|
5037 | n/a | class TestSocketSharing(SocketTCPTest): |
---|
5038 | n/a | # This must be classmethod and not staticmethod or multiprocessing |
---|
5039 | n/a | # won't be able to bootstrap it. |
---|
5040 | n/a | @classmethod |
---|
5041 | n/a | def remoteProcessServer(cls, q): |
---|
5042 | n/a | # Recreate socket from shared data |
---|
5043 | n/a | sdata = q.get() |
---|
5044 | n/a | message = q.get() |
---|
5045 | n/a | |
---|
5046 | n/a | s = socket.fromshare(sdata) |
---|
5047 | n/a | s2, c = s.accept() |
---|
5048 | n/a | |
---|
5049 | n/a | # Send the message |
---|
5050 | n/a | s2.sendall(message) |
---|
5051 | n/a | s2.close() |
---|
5052 | n/a | s.close() |
---|
5053 | n/a | |
---|
5054 | n/a | def testShare(self): |
---|
5055 | n/a | # Transfer the listening server socket to another process |
---|
5056 | n/a | # and service it from there. |
---|
5057 | n/a | |
---|
5058 | n/a | # Create process: |
---|
5059 | n/a | q = multiprocessing.Queue() |
---|
5060 | n/a | p = multiprocessing.Process(target=self.remoteProcessServer, args=(q,)) |
---|
5061 | n/a | p.start() |
---|
5062 | n/a | |
---|
5063 | n/a | # Get the shared socket data |
---|
5064 | n/a | data = self.serv.share(p.pid) |
---|
5065 | n/a | |
---|
5066 | n/a | # Pass the shared socket to the other process |
---|
5067 | n/a | addr = self.serv.getsockname() |
---|
5068 | n/a | self.serv.close() |
---|
5069 | n/a | q.put(data) |
---|
5070 | n/a | |
---|
5071 | n/a | # The data that the server will send us |
---|
5072 | n/a | message = b"slapmahfro" |
---|
5073 | n/a | q.put(message) |
---|
5074 | n/a | |
---|
5075 | n/a | # Connect |
---|
5076 | n/a | s = socket.create_connection(addr) |
---|
5077 | n/a | # listen for the data |
---|
5078 | n/a | m = [] |
---|
5079 | n/a | while True: |
---|
5080 | n/a | data = s.recv(100) |
---|
5081 | n/a | if not data: |
---|
5082 | n/a | break |
---|
5083 | n/a | m.append(data) |
---|
5084 | n/a | s.close() |
---|
5085 | n/a | received = b"".join(m) |
---|
5086 | n/a | self.assertEqual(received, message) |
---|
5087 | n/a | p.join() |
---|
5088 | n/a | |
---|
5089 | n/a | def testShareLength(self): |
---|
5090 | n/a | data = self.serv.share(os.getpid()) |
---|
5091 | n/a | self.assertRaises(ValueError, socket.fromshare, data[:-1]) |
---|
5092 | n/a | self.assertRaises(ValueError, socket.fromshare, data+b"foo") |
---|
5093 | n/a | |
---|
5094 | n/a | def compareSockets(self, org, other): |
---|
5095 | n/a | # socket sharing is expected to work only for blocking socket |
---|
5096 | n/a | # since the internal python timeout value isn't transferred. |
---|
5097 | n/a | self.assertEqual(org.gettimeout(), None) |
---|
5098 | n/a | self.assertEqual(org.gettimeout(), other.gettimeout()) |
---|
5099 | n/a | |
---|
5100 | n/a | self.assertEqual(org.family, other.family) |
---|
5101 | n/a | self.assertEqual(org.type, other.type) |
---|
5102 | n/a | # If the user specified "0" for proto, then |
---|
5103 | n/a | # internally windows will have picked the correct value. |
---|
5104 | n/a | # Python introspection on the socket however will still return |
---|
5105 | n/a | # 0. For the shared socket, the python value is recreated |
---|
5106 | n/a | # from the actual value, so it may not compare correctly. |
---|
5107 | n/a | if org.proto != 0: |
---|
5108 | n/a | self.assertEqual(org.proto, other.proto) |
---|
5109 | n/a | |
---|
5110 | n/a | def testShareLocal(self): |
---|
5111 | n/a | data = self.serv.share(os.getpid()) |
---|
5112 | n/a | s = socket.fromshare(data) |
---|
5113 | n/a | try: |
---|
5114 | n/a | self.compareSockets(self.serv, s) |
---|
5115 | n/a | finally: |
---|
5116 | n/a | s.close() |
---|
5117 | n/a | |
---|
5118 | n/a | def testTypes(self): |
---|
5119 | n/a | families = [socket.AF_INET, socket.AF_INET6] |
---|
5120 | n/a | types = [socket.SOCK_STREAM, socket.SOCK_DGRAM] |
---|
5121 | n/a | for f in families: |
---|
5122 | n/a | for t in types: |
---|
5123 | n/a | try: |
---|
5124 | n/a | source = socket.socket(f, t) |
---|
5125 | n/a | except OSError: |
---|
5126 | n/a | continue # This combination is not supported |
---|
5127 | n/a | try: |
---|
5128 | n/a | data = source.share(os.getpid()) |
---|
5129 | n/a | shared = socket.fromshare(data) |
---|
5130 | n/a | try: |
---|
5131 | n/a | self.compareSockets(source, shared) |
---|
5132 | n/a | finally: |
---|
5133 | n/a | shared.close() |
---|
5134 | n/a | finally: |
---|
5135 | n/a | source.close() |
---|
5136 | n/a | |
---|
5137 | n/a | |
---|
5138 | n/a | @unittest.skipUnless(thread, 'Threading required for this test.') |
---|
5139 | n/a | class SendfileUsingSendTest(ThreadedTCPSocketTest): |
---|
5140 | n/a | """ |
---|
5141 | n/a | Test the send() implementation of socket.sendfile(). |
---|
5142 | n/a | """ |
---|
5143 | n/a | |
---|
5144 | n/a | FILESIZE = (10 * 1024 * 1024) # 10MB |
---|
5145 | n/a | BUFSIZE = 8192 |
---|
5146 | n/a | FILEDATA = b"" |
---|
5147 | n/a | TIMEOUT = 2 |
---|
5148 | n/a | |
---|
5149 | n/a | @classmethod |
---|
5150 | n/a | def setUpClass(cls): |
---|
5151 | n/a | def chunks(total, step): |
---|
5152 | n/a | assert total >= step |
---|
5153 | n/a | while total > step: |
---|
5154 | n/a | yield step |
---|
5155 | n/a | total -= step |
---|
5156 | n/a | if total: |
---|
5157 | n/a | yield total |
---|
5158 | n/a | |
---|
5159 | n/a | chunk = b"".join([random.choice(string.ascii_letters).encode() |
---|
5160 | n/a | for i in range(cls.BUFSIZE)]) |
---|
5161 | n/a | with open(support.TESTFN, 'wb') as f: |
---|
5162 | n/a | for csize in chunks(cls.FILESIZE, cls.BUFSIZE): |
---|
5163 | n/a | f.write(chunk) |
---|
5164 | n/a | with open(support.TESTFN, 'rb') as f: |
---|
5165 | n/a | cls.FILEDATA = f.read() |
---|
5166 | n/a | assert len(cls.FILEDATA) == cls.FILESIZE |
---|
5167 | n/a | |
---|
5168 | n/a | @classmethod |
---|
5169 | n/a | def tearDownClass(cls): |
---|
5170 | n/a | support.unlink(support.TESTFN) |
---|
5171 | n/a | |
---|
5172 | n/a | def accept_conn(self): |
---|
5173 | n/a | self.serv.settimeout(self.TIMEOUT) |
---|
5174 | n/a | conn, addr = self.serv.accept() |
---|
5175 | n/a | conn.settimeout(self.TIMEOUT) |
---|
5176 | n/a | self.addCleanup(conn.close) |
---|
5177 | n/a | return conn |
---|
5178 | n/a | |
---|
5179 | n/a | def recv_data(self, conn): |
---|
5180 | n/a | received = [] |
---|
5181 | n/a | while True: |
---|
5182 | n/a | chunk = conn.recv(self.BUFSIZE) |
---|
5183 | n/a | if not chunk: |
---|
5184 | n/a | break |
---|
5185 | n/a | received.append(chunk) |
---|
5186 | n/a | return b''.join(received) |
---|
5187 | n/a | |
---|
5188 | n/a | def meth_from_sock(self, sock): |
---|
5189 | n/a | # Depending on the mixin class being run return either send() |
---|
5190 | n/a | # or sendfile() method implementation. |
---|
5191 | n/a | return getattr(sock, "_sendfile_use_send") |
---|
5192 | n/a | |
---|
5193 | n/a | # regular file |
---|
5194 | n/a | |
---|
5195 | n/a | def _testRegularFile(self): |
---|
5196 | n/a | address = self.serv.getsockname() |
---|
5197 | n/a | file = open(support.TESTFN, 'rb') |
---|
5198 | n/a | with socket.create_connection(address) as sock, file as file: |
---|
5199 | n/a | meth = self.meth_from_sock(sock) |
---|
5200 | n/a | sent = meth(file) |
---|
5201 | n/a | self.assertEqual(sent, self.FILESIZE) |
---|
5202 | n/a | self.assertEqual(file.tell(), self.FILESIZE) |
---|
5203 | n/a | |
---|
5204 | n/a | def testRegularFile(self): |
---|
5205 | n/a | conn = self.accept_conn() |
---|
5206 | n/a | data = self.recv_data(conn) |
---|
5207 | n/a | self.assertEqual(len(data), self.FILESIZE) |
---|
5208 | n/a | self.assertEqual(data, self.FILEDATA) |
---|
5209 | n/a | |
---|
5210 | n/a | # non regular file |
---|
5211 | n/a | |
---|
5212 | n/a | def _testNonRegularFile(self): |
---|
5213 | n/a | address = self.serv.getsockname() |
---|
5214 | n/a | file = io.BytesIO(self.FILEDATA) |
---|
5215 | n/a | with socket.create_connection(address) as sock, file as file: |
---|
5216 | n/a | sent = sock.sendfile(file) |
---|
5217 | n/a | self.assertEqual(sent, self.FILESIZE) |
---|
5218 | n/a | self.assertEqual(file.tell(), self.FILESIZE) |
---|
5219 | n/a | self.assertRaises(socket._GiveupOnSendfile, |
---|
5220 | n/a | sock._sendfile_use_sendfile, file) |
---|
5221 | n/a | |
---|
5222 | n/a | def testNonRegularFile(self): |
---|
5223 | n/a | conn = self.accept_conn() |
---|
5224 | n/a | data = self.recv_data(conn) |
---|
5225 | n/a | self.assertEqual(len(data), self.FILESIZE) |
---|
5226 | n/a | self.assertEqual(data, self.FILEDATA) |
---|
5227 | n/a | |
---|
5228 | n/a | # empty file |
---|
5229 | n/a | |
---|
5230 | n/a | def _testEmptyFileSend(self): |
---|
5231 | n/a | address = self.serv.getsockname() |
---|
5232 | n/a | filename = support.TESTFN + "2" |
---|
5233 | n/a | with open(filename, 'wb'): |
---|
5234 | n/a | self.addCleanup(support.unlink, filename) |
---|
5235 | n/a | file = open(filename, 'rb') |
---|
5236 | n/a | with socket.create_connection(address) as sock, file as file: |
---|
5237 | n/a | meth = self.meth_from_sock(sock) |
---|
5238 | n/a | sent = meth(file) |
---|
5239 | n/a | self.assertEqual(sent, 0) |
---|
5240 | n/a | self.assertEqual(file.tell(), 0) |
---|
5241 | n/a | |
---|
5242 | n/a | def testEmptyFileSend(self): |
---|
5243 | n/a | conn = self.accept_conn() |
---|
5244 | n/a | data = self.recv_data(conn) |
---|
5245 | n/a | self.assertEqual(data, b"") |
---|
5246 | n/a | |
---|
5247 | n/a | # offset |
---|
5248 | n/a | |
---|
5249 | n/a | def _testOffset(self): |
---|
5250 | n/a | address = self.serv.getsockname() |
---|
5251 | n/a | file = open(support.TESTFN, 'rb') |
---|
5252 | n/a | with socket.create_connection(address) as sock, file as file: |
---|
5253 | n/a | meth = self.meth_from_sock(sock) |
---|
5254 | n/a | sent = meth(file, offset=5000) |
---|
5255 | n/a | self.assertEqual(sent, self.FILESIZE - 5000) |
---|
5256 | n/a | self.assertEqual(file.tell(), self.FILESIZE) |
---|
5257 | n/a | |
---|
5258 | n/a | def testOffset(self): |
---|
5259 | n/a | conn = self.accept_conn() |
---|
5260 | n/a | data = self.recv_data(conn) |
---|
5261 | n/a | self.assertEqual(len(data), self.FILESIZE - 5000) |
---|
5262 | n/a | self.assertEqual(data, self.FILEDATA[5000:]) |
---|
5263 | n/a | |
---|
5264 | n/a | # count |
---|
5265 | n/a | |
---|
5266 | n/a | def _testCount(self): |
---|
5267 | n/a | address = self.serv.getsockname() |
---|
5268 | n/a | file = open(support.TESTFN, 'rb') |
---|
5269 | n/a | with socket.create_connection(address, timeout=2) as sock, file as file: |
---|
5270 | n/a | count = 5000007 |
---|
5271 | n/a | meth = self.meth_from_sock(sock) |
---|
5272 | n/a | sent = meth(file, count=count) |
---|
5273 | n/a | self.assertEqual(sent, count) |
---|
5274 | n/a | self.assertEqual(file.tell(), count) |
---|
5275 | n/a | |
---|
5276 | n/a | def testCount(self): |
---|
5277 | n/a | count = 5000007 |
---|
5278 | n/a | conn = self.accept_conn() |
---|
5279 | n/a | data = self.recv_data(conn) |
---|
5280 | n/a | self.assertEqual(len(data), count) |
---|
5281 | n/a | self.assertEqual(data, self.FILEDATA[:count]) |
---|
5282 | n/a | |
---|
5283 | n/a | # count small |
---|
5284 | n/a | |
---|
5285 | n/a | def _testCountSmall(self): |
---|
5286 | n/a | address = self.serv.getsockname() |
---|
5287 | n/a | file = open(support.TESTFN, 'rb') |
---|
5288 | n/a | with socket.create_connection(address, timeout=2) as sock, file as file: |
---|
5289 | n/a | count = 1 |
---|
5290 | n/a | meth = self.meth_from_sock(sock) |
---|
5291 | n/a | sent = meth(file, count=count) |
---|
5292 | n/a | self.assertEqual(sent, count) |
---|
5293 | n/a | self.assertEqual(file.tell(), count) |
---|
5294 | n/a | |
---|
5295 | n/a | def testCountSmall(self): |
---|
5296 | n/a | count = 1 |
---|
5297 | n/a | conn = self.accept_conn() |
---|
5298 | n/a | data = self.recv_data(conn) |
---|
5299 | n/a | self.assertEqual(len(data), count) |
---|
5300 | n/a | self.assertEqual(data, self.FILEDATA[:count]) |
---|
5301 | n/a | |
---|
5302 | n/a | # count + offset |
---|
5303 | n/a | |
---|
5304 | n/a | def _testCountWithOffset(self): |
---|
5305 | n/a | address = self.serv.getsockname() |
---|
5306 | n/a | file = open(support.TESTFN, 'rb') |
---|
5307 | n/a | with socket.create_connection(address, timeout=2) as sock, file as file: |
---|
5308 | n/a | count = 100007 |
---|
5309 | n/a | meth = self.meth_from_sock(sock) |
---|
5310 | n/a | sent = meth(file, offset=2007, count=count) |
---|
5311 | n/a | self.assertEqual(sent, count) |
---|
5312 | n/a | self.assertEqual(file.tell(), count + 2007) |
---|
5313 | n/a | |
---|
5314 | n/a | def testCountWithOffset(self): |
---|
5315 | n/a | count = 100007 |
---|
5316 | n/a | conn = self.accept_conn() |
---|
5317 | n/a | data = self.recv_data(conn) |
---|
5318 | n/a | self.assertEqual(len(data), count) |
---|
5319 | n/a | self.assertEqual(data, self.FILEDATA[2007:count+2007]) |
---|
5320 | n/a | |
---|
5321 | n/a | # non blocking sockets are not supposed to work |
---|
5322 | n/a | |
---|
5323 | n/a | def _testNonBlocking(self): |
---|
5324 | n/a | address = self.serv.getsockname() |
---|
5325 | n/a | file = open(support.TESTFN, 'rb') |
---|
5326 | n/a | with socket.create_connection(address) as sock, file as file: |
---|
5327 | n/a | sock.setblocking(False) |
---|
5328 | n/a | meth = self.meth_from_sock(sock) |
---|
5329 | n/a | self.assertRaises(ValueError, meth, file) |
---|
5330 | n/a | self.assertRaises(ValueError, sock.sendfile, file) |
---|
5331 | n/a | |
---|
5332 | n/a | def testNonBlocking(self): |
---|
5333 | n/a | conn = self.accept_conn() |
---|
5334 | n/a | if conn.recv(8192): |
---|
5335 | n/a | self.fail('was not supposed to receive any data') |
---|
5336 | n/a | |
---|
5337 | n/a | # timeout (non-triggered) |
---|
5338 | n/a | |
---|
5339 | n/a | def _testWithTimeout(self): |
---|
5340 | n/a | address = self.serv.getsockname() |
---|
5341 | n/a | file = open(support.TESTFN, 'rb') |
---|
5342 | n/a | with socket.create_connection(address, timeout=2) as sock, file as file: |
---|
5343 | n/a | meth = self.meth_from_sock(sock) |
---|
5344 | n/a | sent = meth(file) |
---|
5345 | n/a | self.assertEqual(sent, self.FILESIZE) |
---|
5346 | n/a | |
---|
5347 | n/a | def testWithTimeout(self): |
---|
5348 | n/a | conn = self.accept_conn() |
---|
5349 | n/a | data = self.recv_data(conn) |
---|
5350 | n/a | self.assertEqual(len(data), self.FILESIZE) |
---|
5351 | n/a | self.assertEqual(data, self.FILEDATA) |
---|
5352 | n/a | |
---|
5353 | n/a | # timeout (triggered) |
---|
5354 | n/a | |
---|
5355 | n/a | def _testWithTimeoutTriggeredSend(self): |
---|
5356 | n/a | address = self.serv.getsockname() |
---|
5357 | n/a | file = open(support.TESTFN, 'rb') |
---|
5358 | n/a | with socket.create_connection(address, timeout=0.01) as sock, \ |
---|
5359 | n/a | file as file: |
---|
5360 | n/a | meth = self.meth_from_sock(sock) |
---|
5361 | n/a | self.assertRaises(socket.timeout, meth, file) |
---|
5362 | n/a | |
---|
5363 | n/a | def testWithTimeoutTriggeredSend(self): |
---|
5364 | n/a | conn = self.accept_conn() |
---|
5365 | n/a | conn.recv(88192) |
---|
5366 | n/a | |
---|
5367 | n/a | # errors |
---|
5368 | n/a | |
---|
5369 | n/a | def _test_errors(self): |
---|
5370 | n/a | pass |
---|
5371 | n/a | |
---|
5372 | n/a | def test_errors(self): |
---|
5373 | n/a | with open(support.TESTFN, 'rb') as file: |
---|
5374 | n/a | with socket.socket(type=socket.SOCK_DGRAM) as s: |
---|
5375 | n/a | meth = self.meth_from_sock(s) |
---|
5376 | n/a | self.assertRaisesRegex( |
---|
5377 | n/a | ValueError, "SOCK_STREAM", meth, file) |
---|
5378 | n/a | with open(support.TESTFN, 'rt') as file: |
---|
5379 | n/a | with socket.socket() as s: |
---|
5380 | n/a | meth = self.meth_from_sock(s) |
---|
5381 | n/a | self.assertRaisesRegex( |
---|
5382 | n/a | ValueError, "binary mode", meth, file) |
---|
5383 | n/a | with open(support.TESTFN, 'rb') as file: |
---|
5384 | n/a | with socket.socket() as s: |
---|
5385 | n/a | meth = self.meth_from_sock(s) |
---|
5386 | n/a | self.assertRaisesRegex(TypeError, "positive integer", |
---|
5387 | n/a | meth, file, count='2') |
---|
5388 | n/a | self.assertRaisesRegex(TypeError, "positive integer", |
---|
5389 | n/a | meth, file, count=0.1) |
---|
5390 | n/a | self.assertRaisesRegex(ValueError, "positive integer", |
---|
5391 | n/a | meth, file, count=0) |
---|
5392 | n/a | self.assertRaisesRegex(ValueError, "positive integer", |
---|
5393 | n/a | meth, file, count=-1) |
---|
5394 | n/a | |
---|
5395 | n/a | |
---|
5396 | n/a | @unittest.skipUnless(thread, 'Threading required for this test.') |
---|
5397 | n/a | @unittest.skipUnless(hasattr(os, "sendfile"), |
---|
5398 | n/a | 'os.sendfile() required for this test.') |
---|
5399 | n/a | class SendfileUsingSendfileTest(SendfileUsingSendTest): |
---|
5400 | n/a | """ |
---|
5401 | n/a | Test the sendfile() implementation of socket.sendfile(). |
---|
5402 | n/a | """ |
---|
5403 | n/a | def meth_from_sock(self, sock): |
---|
5404 | n/a | return getattr(sock, "_sendfile_use_sendfile") |
---|
5405 | n/a | |
---|
5406 | n/a | |
---|
5407 | n/a | @unittest.skipUnless(HAVE_SOCKET_ALG, 'AF_ALG required') |
---|
5408 | n/a | class LinuxKernelCryptoAPI(unittest.TestCase): |
---|
5409 | n/a | # tests for AF_ALG |
---|
5410 | n/a | def create_alg(self, typ, name): |
---|
5411 | n/a | sock = socket.socket(socket.AF_ALG, socket.SOCK_SEQPACKET, 0) |
---|
5412 | n/a | try: |
---|
5413 | n/a | sock.bind((typ, name)) |
---|
5414 | n/a | except FileNotFoundError as e: |
---|
5415 | n/a | # type / algorithm is not available |
---|
5416 | n/a | sock.close() |
---|
5417 | n/a | raise unittest.SkipTest(str(e), typ, name) |
---|
5418 | n/a | else: |
---|
5419 | n/a | return sock |
---|
5420 | n/a | |
---|
5421 | n/a | def test_sha256(self): |
---|
5422 | n/a | expected = bytes.fromhex("ba7816bf8f01cfea414140de5dae2223b00361a396" |
---|
5423 | n/a | "177a9cb410ff61f20015ad") |
---|
5424 | n/a | with self.create_alg('hash', 'sha256') as algo: |
---|
5425 | n/a | op, _ = algo.accept() |
---|
5426 | n/a | with op: |
---|
5427 | n/a | op.sendall(b"abc") |
---|
5428 | n/a | self.assertEqual(op.recv(512), expected) |
---|
5429 | n/a | |
---|
5430 | n/a | op, _ = algo.accept() |
---|
5431 | n/a | with op: |
---|
5432 | n/a | op.send(b'a', socket.MSG_MORE) |
---|
5433 | n/a | op.send(b'b', socket.MSG_MORE) |
---|
5434 | n/a | op.send(b'c', socket.MSG_MORE) |
---|
5435 | n/a | op.send(b'') |
---|
5436 | n/a | self.assertEqual(op.recv(512), expected) |
---|
5437 | n/a | |
---|
5438 | n/a | def test_hmac_sha1(self): |
---|
5439 | n/a | expected = bytes.fromhex("effcdf6ae5eb2fa2d27416d5f184df9c259a7c79") |
---|
5440 | n/a | with self.create_alg('hash', 'hmac(sha1)') as algo: |
---|
5441 | n/a | algo.setsockopt(socket.SOL_ALG, socket.ALG_SET_KEY, b"Jefe") |
---|
5442 | n/a | op, _ = algo.accept() |
---|
5443 | n/a | with op: |
---|
5444 | n/a | op.sendall(b"what do ya want for nothing?") |
---|
5445 | n/a | self.assertEqual(op.recv(512), expected) |
---|
5446 | n/a | |
---|
5447 | n/a | # Although it should work with 3.19 and newer the test blocks on |
---|
5448 | n/a | # Ubuntu 15.10 with Kernel 4.2.0-19. |
---|
5449 | n/a | @support.requires_linux_version(4, 3) |
---|
5450 | n/a | def test_aes_cbc(self): |
---|
5451 | n/a | key = bytes.fromhex('06a9214036b8a15b512e03d534120006') |
---|
5452 | n/a | iv = bytes.fromhex('3dafba429d9eb430b422da802c9fac41') |
---|
5453 | n/a | msg = b"Single block msg" |
---|
5454 | n/a | ciphertext = bytes.fromhex('e353779c1079aeb82708942dbe77181a') |
---|
5455 | n/a | msglen = len(msg) |
---|
5456 | n/a | with self.create_alg('skcipher', 'cbc(aes)') as algo: |
---|
5457 | n/a | algo.setsockopt(socket.SOL_ALG, socket.ALG_SET_KEY, key) |
---|
5458 | n/a | op, _ = algo.accept() |
---|
5459 | n/a | with op: |
---|
5460 | n/a | op.sendmsg_afalg(op=socket.ALG_OP_ENCRYPT, iv=iv, |
---|
5461 | n/a | flags=socket.MSG_MORE) |
---|
5462 | n/a | op.sendall(msg) |
---|
5463 | n/a | self.assertEqual(op.recv(msglen), ciphertext) |
---|
5464 | n/a | |
---|
5465 | n/a | op, _ = algo.accept() |
---|
5466 | n/a | with op: |
---|
5467 | n/a | op.sendmsg_afalg([ciphertext], |
---|
5468 | n/a | op=socket.ALG_OP_DECRYPT, iv=iv) |
---|
5469 | n/a | self.assertEqual(op.recv(msglen), msg) |
---|
5470 | n/a | |
---|
5471 | n/a | # long message |
---|
5472 | n/a | multiplier = 1024 |
---|
5473 | n/a | longmsg = [msg] * multiplier |
---|
5474 | n/a | op, _ = algo.accept() |
---|
5475 | n/a | with op: |
---|
5476 | n/a | op.sendmsg_afalg(longmsg, |
---|
5477 | n/a | op=socket.ALG_OP_ENCRYPT, iv=iv) |
---|
5478 | n/a | enc = op.recv(msglen * multiplier) |
---|
5479 | n/a | self.assertEqual(len(enc), msglen * multiplier) |
---|
5480 | n/a | self.assertTrue(enc[:msglen], ciphertext) |
---|
5481 | n/a | |
---|
5482 | n/a | op, _ = algo.accept() |
---|
5483 | n/a | with op: |
---|
5484 | n/a | op.sendmsg_afalg([enc], |
---|
5485 | n/a | op=socket.ALG_OP_DECRYPT, iv=iv) |
---|
5486 | n/a | dec = op.recv(msglen * multiplier) |
---|
5487 | n/a | self.assertEqual(len(dec), msglen * multiplier) |
---|
5488 | n/a | self.assertEqual(dec, msg * multiplier) |
---|
5489 | n/a | |
---|
5490 | n/a | @support.requires_linux_version(4, 3) # see test_aes_cbc |
---|
5491 | n/a | def test_aead_aes_gcm(self): |
---|
5492 | n/a | key = bytes.fromhex('c939cc13397c1d37de6ae0e1cb7c423c') |
---|
5493 | n/a | iv = bytes.fromhex('b3d8cc017cbb89b39e0f67e2') |
---|
5494 | n/a | plain = bytes.fromhex('c3b3c41f113a31b73d9a5cd432103069') |
---|
5495 | n/a | assoc = bytes.fromhex('24825602bd12a984e0092d3e448eda5f') |
---|
5496 | n/a | expected_ct = bytes.fromhex('93fe7d9e9bfd10348a5606e5cafa7354') |
---|
5497 | n/a | expected_tag = bytes.fromhex('0032a1dc85f1c9786925a2e71d8272dd') |
---|
5498 | n/a | |
---|
5499 | n/a | taglen = len(expected_tag) |
---|
5500 | n/a | assoclen = len(assoc) |
---|
5501 | n/a | |
---|
5502 | n/a | with self.create_alg('aead', 'gcm(aes)') as algo: |
---|
5503 | n/a | algo.setsockopt(socket.SOL_ALG, socket.ALG_SET_KEY, key) |
---|
5504 | n/a | algo.setsockopt(socket.SOL_ALG, socket.ALG_SET_AEAD_AUTHSIZE, |
---|
5505 | n/a | None, taglen) |
---|
5506 | n/a | |
---|
5507 | n/a | # send assoc, plain and tag buffer in separate steps |
---|
5508 | n/a | op, _ = algo.accept() |
---|
5509 | n/a | with op: |
---|
5510 | n/a | op.sendmsg_afalg(op=socket.ALG_OP_ENCRYPT, iv=iv, |
---|
5511 | n/a | assoclen=assoclen, flags=socket.MSG_MORE) |
---|
5512 | n/a | op.sendall(assoc, socket.MSG_MORE) |
---|
5513 | n/a | op.sendall(plain, socket.MSG_MORE) |
---|
5514 | n/a | op.sendall(b'\x00' * taglen) |
---|
5515 | n/a | res = op.recv(assoclen + len(plain) + taglen) |
---|
5516 | n/a | self.assertEqual(expected_ct, res[assoclen:-taglen]) |
---|
5517 | n/a | self.assertEqual(expected_tag, res[-taglen:]) |
---|
5518 | n/a | |
---|
5519 | n/a | # now with msg |
---|
5520 | n/a | op, _ = algo.accept() |
---|
5521 | n/a | with op: |
---|
5522 | n/a | msg = assoc + plain + b'\x00' * taglen |
---|
5523 | n/a | op.sendmsg_afalg([msg], op=socket.ALG_OP_ENCRYPT, iv=iv, |
---|
5524 | n/a | assoclen=assoclen) |
---|
5525 | n/a | res = op.recv(assoclen + len(plain) + taglen) |
---|
5526 | n/a | self.assertEqual(expected_ct, res[assoclen:-taglen]) |
---|
5527 | n/a | self.assertEqual(expected_tag, res[-taglen:]) |
---|
5528 | n/a | |
---|
5529 | n/a | # create anc data manually |
---|
5530 | n/a | pack_uint32 = struct.Struct('I').pack |
---|
5531 | n/a | op, _ = algo.accept() |
---|
5532 | n/a | with op: |
---|
5533 | n/a | msg = assoc + plain + b'\x00' * taglen |
---|
5534 | n/a | op.sendmsg( |
---|
5535 | n/a | [msg], |
---|
5536 | n/a | ([socket.SOL_ALG, socket.ALG_SET_OP, pack_uint32(socket.ALG_OP_ENCRYPT)], |
---|
5537 | n/a | [socket.SOL_ALG, socket.ALG_SET_IV, pack_uint32(len(iv)) + iv], |
---|
5538 | n/a | [socket.SOL_ALG, socket.ALG_SET_AEAD_ASSOCLEN, pack_uint32(assoclen)], |
---|
5539 | n/a | ) |
---|
5540 | n/a | ) |
---|
5541 | n/a | res = op.recv(len(msg)) |
---|
5542 | n/a | self.assertEqual(expected_ct, res[assoclen:-taglen]) |
---|
5543 | n/a | self.assertEqual(expected_tag, res[-taglen:]) |
---|
5544 | n/a | |
---|
5545 | n/a | # decrypt and verify |
---|
5546 | n/a | op, _ = algo.accept() |
---|
5547 | n/a | with op: |
---|
5548 | n/a | msg = assoc + expected_ct + expected_tag |
---|
5549 | n/a | op.sendmsg_afalg([msg], op=socket.ALG_OP_DECRYPT, iv=iv, |
---|
5550 | n/a | assoclen=assoclen) |
---|
5551 | n/a | res = op.recv(len(msg)) |
---|
5552 | n/a | self.assertEqual(plain, res[assoclen:-taglen]) |
---|
5553 | n/a | |
---|
5554 | n/a | @support.requires_linux_version(4, 3) # see test_aes_cbc |
---|
5555 | n/a | def test_drbg_pr_sha256(self): |
---|
5556 | n/a | # deterministic random bit generator, prediction resistance, sha256 |
---|
5557 | n/a | with self.create_alg('rng', 'drbg_pr_sha256') as algo: |
---|
5558 | n/a | extra_seed = os.urandom(32) |
---|
5559 | n/a | algo.setsockopt(socket.SOL_ALG, socket.ALG_SET_KEY, extra_seed) |
---|
5560 | n/a | op, _ = algo.accept() |
---|
5561 | n/a | with op: |
---|
5562 | n/a | rn = op.recv(32) |
---|
5563 | n/a | self.assertEqual(len(rn), 32) |
---|
5564 | n/a | |
---|
5565 | n/a | def test_sendmsg_afalg_args(self): |
---|
5566 | n/a | sock = socket.socket(socket.AF_ALG, socket.SOCK_SEQPACKET, 0) |
---|
5567 | n/a | with sock: |
---|
5568 | n/a | with self.assertRaises(TypeError): |
---|
5569 | n/a | sock.sendmsg_afalg() |
---|
5570 | n/a | |
---|
5571 | n/a | with self.assertRaises(TypeError): |
---|
5572 | n/a | sock.sendmsg_afalg(op=None) |
---|
5573 | n/a | |
---|
5574 | n/a | with self.assertRaises(TypeError): |
---|
5575 | n/a | sock.sendmsg_afalg(1) |
---|
5576 | n/a | |
---|
5577 | n/a | with self.assertRaises(TypeError): |
---|
5578 | n/a | sock.sendmsg_afalg(op=socket.ALG_OP_ENCRYPT, assoclen=None) |
---|
5579 | n/a | |
---|
5580 | n/a | with self.assertRaises(TypeError): |
---|
5581 | n/a | sock.sendmsg_afalg(op=socket.ALG_OP_ENCRYPT, assoclen=-1) |
---|
5582 | n/a | |
---|
5583 | n/a | |
---|
5584 | n/a | def test_main(): |
---|
5585 | n/a | tests = [GeneralModuleTests, BasicTCPTest, TCPCloserTest, TCPTimeoutTest, |
---|
5586 | n/a | TestExceptions, BufferIOTest, BasicTCPTest2, BasicUDPTest, UDPTimeoutTest ] |
---|
5587 | n/a | |
---|
5588 | n/a | tests.extend([ |
---|
5589 | n/a | NonBlockingTCPTests, |
---|
5590 | n/a | FileObjectClassTestCase, |
---|
5591 | n/a | UnbufferedFileObjectClassTestCase, |
---|
5592 | n/a | LineBufferedFileObjectClassTestCase, |
---|
5593 | n/a | SmallBufferedFileObjectClassTestCase, |
---|
5594 | n/a | UnicodeReadFileObjectClassTestCase, |
---|
5595 | n/a | UnicodeWriteFileObjectClassTestCase, |
---|
5596 | n/a | UnicodeReadWriteFileObjectClassTestCase, |
---|
5597 | n/a | NetworkConnectionNoServer, |
---|
5598 | n/a | NetworkConnectionAttributesTest, |
---|
5599 | n/a | NetworkConnectionBehaviourTest, |
---|
5600 | n/a | ContextManagersTest, |
---|
5601 | n/a | InheritanceTest, |
---|
5602 | n/a | NonblockConstantTest |
---|
5603 | n/a | ]) |
---|
5604 | n/a | tests.append(BasicSocketPairTest) |
---|
5605 | n/a | tests.append(TestUnixDomain) |
---|
5606 | n/a | tests.append(TestLinuxAbstractNamespace) |
---|
5607 | n/a | tests.extend([TIPCTest, TIPCThreadableTest]) |
---|
5608 | n/a | tests.extend([BasicCANTest, CANTest]) |
---|
5609 | n/a | tests.extend([BasicRDSTest, RDSTest]) |
---|
5610 | n/a | tests.append(LinuxKernelCryptoAPI) |
---|
5611 | n/a | tests.extend([ |
---|
5612 | n/a | CmsgMacroTests, |
---|
5613 | n/a | SendmsgUDPTest, |
---|
5614 | n/a | RecvmsgUDPTest, |
---|
5615 | n/a | RecvmsgIntoUDPTest, |
---|
5616 | n/a | SendmsgUDP6Test, |
---|
5617 | n/a | RecvmsgUDP6Test, |
---|
5618 | n/a | RecvmsgRFC3542AncillaryUDP6Test, |
---|
5619 | n/a | RecvmsgIntoRFC3542AncillaryUDP6Test, |
---|
5620 | n/a | RecvmsgIntoUDP6Test, |
---|
5621 | n/a | SendmsgTCPTest, |
---|
5622 | n/a | RecvmsgTCPTest, |
---|
5623 | n/a | RecvmsgIntoTCPTest, |
---|
5624 | n/a | SendmsgSCTPStreamTest, |
---|
5625 | n/a | RecvmsgSCTPStreamTest, |
---|
5626 | n/a | RecvmsgIntoSCTPStreamTest, |
---|
5627 | n/a | SendmsgUnixStreamTest, |
---|
5628 | n/a | RecvmsgUnixStreamTest, |
---|
5629 | n/a | RecvmsgIntoUnixStreamTest, |
---|
5630 | n/a | RecvmsgSCMRightsStreamTest, |
---|
5631 | n/a | RecvmsgIntoSCMRightsStreamTest, |
---|
5632 | n/a | # These are slow when setitimer() is not available |
---|
5633 | n/a | InterruptedRecvTimeoutTest, |
---|
5634 | n/a | InterruptedSendTimeoutTest, |
---|
5635 | n/a | TestSocketSharing, |
---|
5636 | n/a | SendfileUsingSendTest, |
---|
5637 | n/a | SendfileUsingSendfileTest, |
---|
5638 | n/a | ]) |
---|
5639 | n/a | |
---|
5640 | n/a | thread_info = support.threading_setup() |
---|
5641 | n/a | support.run_unittest(*tests) |
---|
5642 | n/a | support.threading_cleanup(*thread_info) |
---|
5643 | n/a | |
---|
5644 | n/a | if __name__ == "__main__": |
---|
5645 | n/a | test_main() |
---|