Debian Codegraph @

pypy/module/_socket/test/apptest_socket.py

raw symbols SCIP
1 # spaceconfig = {"usemodules": ["_socket", "_weakref", "array", "struct", "select", "unicodedata"]}
2 import os
3 import sys
4 import pytest
5
6
7 def test_module():
8 import _socket
9 assert _socket.socket.__name__ == 'socket'
10 assert _socket.socket.__module__ == '_socket'
11
12 def test_overflow_errors():
13 import _socket
14 pytest.raises(OverflowError, _socket.getservbyport, -1)
15 pytest.raises(OverflowError, _socket.getservbyport, 65536)
16
17 def test_ntoa_exception():
18 import _socket
19 pytest.raises(_socket.error, _socket.inet_ntoa, b"ab")
20
21 def test_aton_exceptions():
22 import _socket
23 tests = ["127.0.0.256", "127.0.0.255555555555555555", "127.2b.0.0",
24 "127.2.0.0.1", "127.2.0."]
25 for ip in tests:
26 pytest.raises(_socket.error, _socket.inet_aton, ip)
27
28 def test_ntop_exceptions():
29 import _socket
30 if not hasattr(_socket, 'inet_ntop'):
31 pytest.skip('No socket.inet_pton on this platform')
32 for family, packed, exception in \
33 [(_socket.AF_INET + _socket.AF_INET6, b"", _socket.error),
34 (_socket.AF_INET, b"a", ValueError),
35 (_socket.AF_INET6, b"a", ValueError),
36 (_socket.AF_INET, "aa\u2222a", TypeError)]:
37 pytest.raises(exception, _socket.inet_ntop, family, packed)
38
39 def test_pton_exceptions():
40 import _socket
41 if not hasattr(_socket, 'inet_pton'):
42 pytest.skip('No socket.inet_pton on this platform')
43 tests = [
44 (_socket.AF_INET + _socket.AF_INET6, ""),
45 (_socket.AF_INET, "127.0.0.256"),
46 (_socket.AF_INET, "127.0.0.255555555555555555"),
47 (_socket.AF_INET, "127.2b.0.0"),
48 (_socket.AF_INET, "127.2.0.0.1"),
49 (_socket.AF_INET, "127.2..0"),
50 (_socket.AF_INET6, "127.0.0.1"),
51 (_socket.AF_INET6, "1::2::3"),
52 (_socket.AF_INET6, "1:1:1:1:1:1:1:1:1"),
53 (_socket.AF_INET6, "1:1:1:1:1:1:1:1::"),
54 (_socket.AF_INET6, "1:1:1::1:1:1:1:1"),
55 (_socket.AF_INET6, "1::22222:1"),
56 (_socket.AF_INET6, "1::eg"),
57 ]
58 for family, ip in tests:
59 pytest.raises(_socket.error, _socket.inet_pton, family, ip)
60
61 def test_newsocket_error():
62 import _socket
63 pytest.raises(_socket.error, _socket.socket, 10001, _socket.SOCK_STREAM, 0)
64
65 def test_socket_fileno():
66 import _socket
67 s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
68 assert s.fileno() > -1
69 assert isinstance(s.fileno(), int)
70
71 def test_socket_repr():
72 import _socket
73 s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
74 try:
75 expected = ('<socket object, fd=%s, family=%s, type=%s, proto=%s>'
76 % (s.fileno(), s.family, s.type, s.proto))
77 assert repr(s) == expected
78 finally:
79 s.close()
80 expected = ('<socket object, fd=-1, family=%s, type=%s, proto=%s>'
81 % (s.family, s.type, s.proto))
82 assert repr(s) == expected
83
84 def test_socket_close():
85 import _socket, os
86 s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
87 fileno = s.fileno()
88 assert s.fileno() >= 0
89 s.close()
90 assert s.fileno() < 0
91 s.close()
92 if os.name != 'nt':
93 pytest.raises(OSError, os.close, fileno)
94
95 @pytest.mark.skipif(sys.platform == 'win32', reason="no fileno on windows")
96 def test_socket_close_exception():
97 import _socket, errno
98 s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
99 _socket.socket(fileno=s.fileno()).close()
100 e = pytest.raises(OSError, s.close)
101 assert e.value.errno in (errno.EBADF, errno.ENOTSOCK)
102
103 @pytest.mark.skipif(sys.platform == 'win32', reason="no fileno on windows")
104 def test_setblocking_invalidfd():
105 import _socket
106 s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
107 _socket.socket(fileno=s.fileno()).close()
108 pytest.raises(OSError, s.setblocking, False)
109
110 def test_socket_connect():
111 import _socket
112 s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
113 try:
114 s.connect(("www.python.org", 80))
115 except _socket.gaierror as ex:
116 pytest.skip("GAIError - probably no connection: %s" % str(ex.args))
117 except ConnectionRefusedError as ex:
118 pytest.skip("Connection Refused - probably no connection: %s" % str(ex.args))
119 name = s.getpeername() # Will raise socket.error if not connected
120 assert name[1] == 80
121 s.close()
122
123 def test_socket_connect_ex():
124 import _socket
125 s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
126 # The following might fail if the DNS redirects failed requests to a
127 # catch-all address (i.e. opendns).
128 # Make sure we get an app-level error, not an interp one.
129 pytest.raises(_socket.gaierror, s.connect_ex, ("wrong.invalid", 80))
130 s.close()
131
132 def test_socket_connect_typeerrors():
133 tests = [
134 "",
135 "80",
136 ("80",),
137 ("80", "80"),
138 (80, 80),
139 ]
140 import _socket
141 s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
142 for args in tests:
143 pytest.raises((TypeError, ValueError), s.connect, args)
144 s.close()
145
146 def test_bigport():
147 import _socket
148 s = _socket.socket()
149 exc = pytest.raises(OverflowError, s.connect, ("localhost", -1))
150 assert "port must be 0-65535." in str(exc.value)
151 exc = pytest.raises(OverflowError, s.connect, ("localhost", 1000000))
152 assert "port must be 0-65535." in str(exc.value)
153 s = _socket.socket(_socket.AF_INET6)
154 exc = pytest.raises(OverflowError, s.connect, ("::1", 1234, 1048576))
155 assert "flowinfo must be 0-1048575." in str(exc.value)
156
157 def test_NtoH():
158 import _socket as socket
159 # This checks that htons etc. are their own inverse,
160 # when looking at the lower 16 or 32 bits. It also
161 # checks that we get OverflowErrors when calling with -1,
162 # or (for XtoXl()) with too large values. For XtoXs()
163 # large values are silently truncated instead, like CPython.
164 sizes = {socket.htonl: 32, socket.ntohl: 32,
165 socket.htons: 16, socket.ntohs: 16}
166 for func, size in sizes.items():
167 mask = (1 << size) - 1
168 for i in (0, 1, 0xffff, 0xffff0000, 2, 0x01234567, 0x76543210):
169 assert i & mask == func(func(i&mask)) & mask
170
171 swapped = func(mask)
172 assert swapped & mask == mask
173 pytest.raises(OverflowError, func, -1)
174 if size > 16: # else, values too large are ignored
175 pytest.raises(OverflowError, func, 2 ** size)
176
177 def test_newsocket():
178 import _socket
179 s = _socket.socket()
180
181 def test_subclass():
182 from _socket import socket
183 class MySock(socket):
184 blah = 123
185 s = MySock()
186 assert s.blah == 123
187
188 def test_getsetsockopt():
189 import _socket as socket
190 import struct
191 # A socket should start with reuse == 0
192 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
193 reuse = s.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
194 assert reuse == 0
195 #
196 pytest.raises(TypeError, s.setsockopt, socket.SOL_SOCKET,
197 socket.SO_REUSEADDR, 2 ** 31)
198 pytest.raises(TypeError, s.setsockopt, socket.SOL_SOCKET,
199 socket.SO_REUSEADDR, 2 ** 32 + 1)
200 assert s.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 0
201 #
202 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
203 reuse = s.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
204 assert reuse != 0
205 # String case
206 intsize = struct.calcsize('i')
207 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
208 reusestr = s.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,
209 intsize)
210 (reuse,) = struct.unpack('i', reusestr)
211 assert reuse == 0
212 reusestr = struct.pack('i', 1)
213 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, reusestr)
214 reusestr = s.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,
215 intsize)
216 (reuse,) = struct.unpack('i', reusestr)
217 assert reuse != 0
218 # try to call setsockopt() with a buffer argument
219 reusestr = struct.pack('i', 0)
220 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, memoryview(reusestr))
221 reusestr = s.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,
222 intsize)
223 (reuse,) = struct.unpack('i', reusestr)
224 assert reuse == 0
225
226 def test_getsetsockopt_zero():
227 # related to issue #2561: when specifying the buffer size param:
228 # if 0 or None, should return the setted value,
229 # otherwise an empty buffer of the specified size
230 import _socket
231 s = _socket.socket()
232 assert s.getsockopt(_socket.IPPROTO_TCP, _socket.TCP_NODELAY, 0) == 0
233 ret = s.getsockopt(_socket.IPPROTO_TCP, _socket.TCP_NODELAY, 2)
234 if len(ret) == 1:
235 # win32 returns a byte-as-bool
236 assert ret == b'\x00'
237 else:
238 assert ret == b'\x00\x00'
239 s.setsockopt(_socket.IPPROTO_TCP, _socket.TCP_NODELAY, True)
240 assert s.getsockopt(_socket.IPPROTO_TCP, _socket.TCP_NODELAY, 0) != 0
241 s.setsockopt(_socket.IPPROTO_TCP, _socket.TCP_NODELAY, 1)
242 assert s.getsockopt(_socket.IPPROTO_TCP, _socket.TCP_NODELAY, 0) != 0
243
244 def test_getsockopt_bad_length():
245 import _socket
246 s = _socket.socket()
247 buf = s.getsockopt(_socket.IPPROTO_TCP, _socket.TCP_NODELAY, 1024)
248 if len(buf) == 1:
249 # win32 returns a byte-as-bool
250 assert buf == b'\x00'
251 else:
252 assert buf == b'\x00' * 4
253 pytest.raises(_socket.error, s.getsockopt,
254 _socket.IPPROTO_TCP, _socket.TCP_NODELAY, 1025)
255 pytest.raises(_socket.error, s.getsockopt,
256 _socket.IPPROTO_TCP, _socket.TCP_NODELAY, -1)
257
258 def test_socket_ioctl():
259 import _socket, sys
260 if sys.platform != 'win32':
261 pytest.skip("win32 only")
262 assert hasattr(_socket.socket, 'ioctl')
263 assert hasattr(_socket, 'SIO_RCVALL')
264 assert hasattr(_socket, 'RCVALL_ON')
265 assert hasattr(_socket, 'RCVALL_OFF')
266 assert hasattr(_socket, 'SIO_KEEPALIVE_VALS')
267 s = _socket.socket()
268 pytest.raises(ValueError, s.ioctl, -1, None)
269 s.ioctl(_socket.SIO_KEEPALIVE_VALS, (1, 100, 100))
270
271 @pytest.mark.skipif(os.name != 'nt', reason="win32 only")
272 def test_socket_sharelocal():
273 import _socket, sys, os
274 assert hasattr(_socket.socket, 'share')
275 s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
276 with pytest.raises(OSError):
277 s.listen()
278 s.bind(('localhost', 0))
279 s.listen(1)
280 data = s.share(os.getpid())
281 # emulate socket.fromshare
282 s2 = _socket.socket(0, 0, 0, data)
283 try:
284 assert s.gettimeout() == s2.gettimeout()
285 assert s.family == s2.family
286 assert s.type == s2.type
287 if s.proto != 0:
288 assert s.proto == s2.proto
289 finally:
290 s.close()
291 s2.close()
292
293 def test_dup():
294 import _socket as socket, os
295 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
296 s.bind(('localhost', 0))
297 fd = socket.dup(s.fileno())
298 assert s.fileno() != fd
299 if os.name != 'nt':
300 assert os.get_inheritable(s.fileno()) is False
301 assert os.get_inheritable(fd) is False
302 s_dup = socket.socket(fileno=fd)
303 s_dup.close()
304 s.close()
305
306 def test_dup_error():
307 import _socket
308 pytest.raises(_socket.error, _socket.dup, 123456)
309
310 @pytest.mark.skipif(sys.platform == 'win32', reason="no recvmsg on win32")
311 @pytest.mark.skipif(sys.platform == 'darwin', reason="no MSG_ERRQUEUE on macos")
312 def test_recvmsg_issue2649():
313 import _socket as socket
314 listener = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
315 listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
316 listener.bind(('127.0.0.1', 1234))
317
318 s = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
319 s.sendto(b'x', ('127.0.0.1', 1234))
320 with pytest.raises(BlockingIOError):
321 queue = s.recvmsg(1024, 1024, socket.MSG_ERRQUEUE)
322
323 def test_buffer():
324 # Test that send/sendall/sendto accept a buffer as arg
325 import _socket
326 s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
327 # XXX temporarily we use python.org to test, will have more robust tests
328 # in the absence of a network connection later when more parts of the
329 # socket API are implemented. Currently skip the test if there is no
330 # connection.
331 try:
332 s.connect(("www.python.org", 80))
333 except _socket.gaierror as ex:
334 pytest.skip("GAIError - probably no connection: %s" % str(ex.args))
335 except ConnectionRefusedError as ex:
336 pytest.skip("Connection Refused - probably no connection: %s" % str(ex.args))
337 exc = pytest.raises(TypeError, s.send, None)
338 assert str(exc.value).startswith("a bytes-like object is required,")
339 assert s.send(memoryview(b'')) == 0
340 assert s.sendall(memoryview(b'')) is None
341 exc = pytest.raises(TypeError, s.send, '')
342 assert str(exc.value).startswith("a bytes-like object is required,")
343 pytest.raises(TypeError, s.sendall, '')
344 s.close()
345 s = _socket.socket(_socket.AF_INET, _socket.SOCK_DGRAM, 0)
346 s.sendto(memoryview(b''), ('localhost', 9)) # Send to discard port.
347 s.close()
348
349 def test_listen_default():
350 import _socket, sys
351 if sys.platform == 'win32':
352 with pytest.raises(OSError):
353 _socket.socket().listen()
354 else:
355 _socket.socket().listen()
356 assert isinstance(_socket.SOMAXCONN, int)
357
358 def test_unix_socket_connect():
359 import _socket, os, tempfile
360 if not hasattr(_socket, 'AF_UNIX'):
361 pytest.skip('AF_UNIX not supported.')
362 udir = tempfile.mkdtemp()
363 oldcwd = os.getcwd()
364 os.chdir(udir)
365 try:
366 for sockpath in ['app_test_unix_socket_connect',
367 b'b_app_test_unix_socket_connect',
368 bytearray(b'ba_app_test_unix_socket_connect')]:
369
370 serversock = _socket.socket(_socket.AF_UNIX)
371 serversock.bind(sockpath)
372 serversock.listen(1)
373
374 clientsock = _socket.socket(_socket.AF_UNIX)
375 clientsock.connect(sockpath)
376 fileno, addr = serversock._accept()
377 s = _socket.socket(fileno=fileno)
378 assert not addr
379
380 s.send(b'X')
381 data = clientsock.recv(100)
382 assert data == b'X'
383 clientsock.send(b'Y')
384 data = s.recv(100)
385 assert data == b'Y'
386
387 clientsock.close()
388 s.close()
389 finally:
390 os.chdir(oldcwd)
391
392 def test_subclass_init():
393 # Socket is not created in __new__, but in __init__.
394 import _socket as socket
395 class Socket_IPV6(socket.socket):
396 def __init__(self):
397 socket.socket.__init__(self, family=socket.AF_INET6)
398 assert Socket_IPV6().family == socket.AF_INET6
399
400 def test_subclass_noinit():
401 from _socket import socket
402 class MySock(socket):
403 def __init__(self, *args):
404 pass # don't call super
405 s = MySock()
406 assert s.type == 0
407 assert s.proto == 0
408 assert s.family == 0
409 assert s.fileno() < 0
410 pytest.raises(OSError, s.bind, ('localhost', 0))
411
412 def test_dealloc_warn():
413 import _socket
414 import gc
415 import warnings
416
417 s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
418 r = repr(s)
419 gc.collect()
420 with warnings.catch_warnings(record=True) as w:
421 warnings.simplefilter('always')
422 s = None
423 gc.collect()
424 assert len(w) == 1, [str(warning) for warning in w]
425 assert r in str(w[0])
426
427 def test_invalid_fd():
428 import _socket
429 pytest.raises(ValueError, _socket.socket, fileno=-1)
430 pytest.raises(TypeError, _socket.socket, fileno=42.5)
431
432 def test_socket_non_inheritable():
433 import _socket, os
434 s1 = _socket.socket()
435 if os.name == 'nt':
436 with pytest.raises(OSError):
437 os.get_inheritable(s1.fileno())
438 else:
439 assert os.get_inheritable(s1.fileno()) is False
440 s1.close()
441
442 def test_socketpair_non_inheritable():
443 import _socket, os
444 if not hasattr(_socket, 'socketpair'):
445 pytest.skip("no socketpair")
446 s1, s2 = _socket.socketpair()
447 assert os.get_inheritable(s1.fileno()) is False
448 assert os.get_inheritable(s2.fileno()) is False
449 s1.close()
450 s2.close()
451
452 def test_hostname_unicode():
453 import _socket
454 domain = u"испытание.pythontest.net"
455 try:
456 _socket.gethostbyname(domain)
457 _socket.gethostbyname_ex(domain)
458 _socket.getaddrinfo(domain, 0, _socket.AF_UNSPEC, _socket.SOCK_STREAM)
459 except _socket.gaierror as ex:
460 pytest.skip("GAIError - probably no connection: %s" % str(ex.args))
461 s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
462 pytest.raises(TypeError, s.connect, (domain + '\x00', 80))
463
464 def test_socket_close_via_close():
465 import _socket
466 sock = _socket.socket()
467 try:
468 sock.bind(('localhost', 0))
469 _socket.close(sock.fileno())
470 with pytest.raises(OSError):
471 sock.listen(1)
472 with pytest.raises(OSError):
473 _socket.close(sock.fileno())
474 finally:
475 with pytest.raises(OSError):
476 sock.close()
477
478 def test_socket_get_values_from_fd():
479 import _socket
480 if hasattr(_socket, "SOCK_DGRAM"):
481 s = _socket.socket(_socket.AF_INET, _socket.SOCK_DGRAM)
482 try:
483 s.bind(('localhost', 0))
484 fd = s.fileno()
485 s2 = _socket.socket(fileno=fd)
486 try:
487 # detach old fd to avoid double close
488 s.detach()
489 assert s2.fileno() == fd
490 assert s2.family == _socket.AF_INET
491 assert s2.type == _socket.SOCK_DGRAM
492
493 finally:
494 s2.close()
495 finally:
496 s.close()
497
498 def test_socket_init_non_blocking():
499 import _socket
500 if not hasattr(_socket, "SOCK_NONBLOCK"):
501 pytest.skip("no SOCK_NONBLOCK")
502 s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM |
503 _socket.SOCK_NONBLOCK)
504 assert s.getblocking() == False
505 assert s.gettimeout() == 0.0
506
507 def test_socket_consistent_sock_type():
508 import _socket
509 SOCK_NONBLOCK = getattr(_socket, 'SOCK_NONBLOCK', 0)
510 SOCK_CLOEXEC = getattr(_socket, 'SOCK_CLOEXEC', 0)
511 sock_type = _socket.SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC
512
513 s = _socket.socket(_socket.AF_INET, sock_type)
514 try:
515 assert s.type == _socket.SOCK_STREAM
516 s.settimeout(1)
517 assert s.type == _socket.SOCK_STREAM
518 s.settimeout(0)
519 assert s.type == _socket.SOCK_STREAM
520 s.setblocking(True)
521 assert s.type == _socket.SOCK_STREAM
522 s.setblocking(False)
523 assert s.type == _socket.SOCK_STREAM
524 finally:
525 s.close()
526
527
528 @pytest.mark.skipif(not hasattr(os, 'getpid'),
529 reason="AF_NETLINK needs os.getpid()")
530 def test_connect_to_kernel_netlink_routing_socket():
531 import _socket, os
532 if not hasattr(_socket, 'AF_NETLINK'):
533 pytest.skip("no AF_NETLINK on this platform")
534 s = _socket.socket(_socket.AF_NETLINK, _socket.SOCK_DGRAM,
535 _socket.NETLINK_ROUTE)
536 assert s.getsockname() == (0, 0)
537 s.bind((0, 0))
538 a, b = s.getsockname()
539 assert a == os.getpid()
540 assert b == 0
541
542
543 @pytest.mark.skipif(not hasattr(os, 'getuid') or os.getuid() != 0,
544 reason="AF_PACKET needs to be root for testing")
545 def test_convert_between_tuple_and_sockaddr_ll():
546 import _socket
547 if not hasattr(_socket, 'AF_PACKET'):
548 pytest.skip("no AF_PACKET on this platform")
549 s = _socket.socket(_socket.AF_PACKET, _socket.SOCK_RAW)
550 assert s.getsockname() == ('', 0, 0, 0, b''), 's.getsockname %s' % str(s.getsockname())
551 s.bind(('lo', 123))
552 a, b, c, d, e = s.getsockname()
553 assert (a, b, c) == ('lo', 123, 0)
554 assert isinstance(d, int)
555 assert isinstance(e, bytes)
556 assert 0 <= len(e) <= 8
557 s.close()
558
559
560 def test_tcp_timeout():
561 import _socket
562 serv = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
563 serv.bind(('localhost', 0))
564 serv.listen(1)
565 from _socket import timeout
566 def raise_timeout():
567 serv.settimeout(1.0)
568 serv._accept()
569 try:
570 pytest.raises(timeout, raise_timeout)
571 finally:
572 serv.close()
573
574 def test_tcp_timeout_zero():
575 import _socket
576 serv = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
577 serv.bind(('localhost', 0))
578 serv.listen(1)
579 from _socket import error
580 def raise_error():
581 serv.settimeout(0.0)
582 foo = serv._accept()
583 try:
584 pytest.raises(error, raise_error)
585 finally:
586 serv.close()
587
588 @pytest.mark.skipif(os.name == 'nt', reason="win32 has additional buffering")
589 def test_tcp_recv_send_timeout():
590 import _socket
591 serv = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
592 serv.bind(('localhost', 0))
593 serv.listen(1)
594 from _socket import socket, timeout, SOL_SOCKET, SO_RCVBUF, SO_SNDBUF
595 import sys
596 cli = socket()
597 cli.settimeout(1.0)
598 cli.connect(serv.getsockname())
599 fileno, addr = serv._accept()
600 t = socket(fileno=fileno)
601 # test recv() timeout
602 t.send(b'*')
603 buf = cli.recv(100)
604 assert buf == b'*'
605 pytest.raises(timeout, cli.recv, 100)
606 # test that send() works
607 count = cli.send(b'!')
608 assert count == 1
609 buf = t.recv(1)
610 assert buf == b'!'
611 # test that sendall() works
612 count = cli.sendall(b'?')
613 assert count is None
614 buf = t.recv(1)
615 assert buf == b'?'
616 # speed up filling the buffers
617 t.setsockopt(SOL_SOCKET, SO_RCVBUF, 4096)
618 cli.setsockopt(SOL_SOCKET, SO_SNDBUF, 4096)
619 # test send() timeout
620 count = 0
621 if sys.platform != 'win32':
622 # windows never fills the buffer
623 try:
624 while 1:
625 count += cli.send(b'foobar' * 70)
626 if sys.platform == 'darwin':
627 # MacOS will auto-tune up to 512k
628 # (net.inet.tcp.doauto{rcv,snd}buf sysctls)
629 assert count < 1000000
630 else:
631 assert count < 100000
632 except timeout:
633 pass
634 t.recv(count)
635 # test sendall() timeout
636 try:
637 while 1:
638 cli.sendall(b'foobar' * 70)
639 except timeout:
640 pass
641 # done
642 cli.close()
643 t.close()
644 serv.close()
645
646 def test_tcp_getblocking():
647 import _socket
648 serv = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
649 serv.bind(('localhost', 0))
650 serv.listen(1)
651 serv.setblocking(True)
652 assert serv.getblocking()
653 serv.setblocking(False)
654 assert not serv.getblocking()
655 serv.close()
656
657 def test_tcp_recv_into():
658 import _socket as socket
659 import array
660 import _io
661 serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
662 serv.bind(('localhost', 0))
663 serv.listen(1)
664 MSG = b'dupa was here\n'
665 cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
666 cli.connect(serv.getsockname())
667 fileno, addr = serv._accept()
668 conn = socket.socket(fileno=fileno)
669 buf = memoryview(MSG)
670 conn.send(buf)
671 buf = array.array('b', b' ' * 1024)
672 nbytes = cli.recv_into(buf)
673 assert nbytes == len(MSG)
674 msg = buf.tobytes()[:len(MSG)]
675 assert msg == MSG
676
677 conn.send(MSG)
678 buf = bytearray(1024)
679 nbytes = cli.recv_into(memoryview(buf))
680 assert nbytes == len(MSG)
681 msg = buf[:len(MSG)]
682 assert msg == MSG
683
684 # A case where rwbuffer.get_raw_address() fails
685 conn.send(MSG)
686 buf = _io.BytesIO(b' ' * 1024)
687 m = buf.getbuffer()
688 nbytes = cli.recv_into(m)
689 assert nbytes == len(MSG)
690 msg = buf.getvalue()[:len(MSG)]
691 assert msg == MSG
692 conn.close()
693 serv.close()
694
695 def test_tcp_recvfrom_into():
696 import _socket as socket
697 import array
698 import _io
699 serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
700 serv.bind(('localhost', 0))
701 serv.listen(1)
702 MSG = b'dupa was here\n'
703 cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
704 cli.connect(serv.getsockname())
705 fileno, addr = serv._accept()
706 conn = socket.socket(fileno=fileno)
707 buf = memoryview(MSG)
708 conn.send(buf)
709 buf = array.array('b', b' ' * 1024)
710 nbytes, addr = cli.recvfrom_into(buf)
711 assert nbytes == len(MSG)
712 msg = buf.tobytes()[:len(MSG)]
713 assert msg == MSG
714
715 conn.send(MSG)
716 buf = bytearray(1024)
717 nbytes, addr = cli.recvfrom_into(memoryview(buf))
718 assert nbytes == len(MSG)
719 msg = buf[:len(MSG)]
720 assert msg == MSG
721
722 # A case where rwbuffer.get_raw_address() fails
723 conn.send(MSG)
724 buf = _io.BytesIO(b' ' * 1024)
725 nbytes, addr = cli.recvfrom_into(buf.getbuffer())
726 assert nbytes == len(MSG)
727 msg = buf.getvalue()[:len(MSG)]
728 assert msg == MSG
729
730 conn.send(MSG)
731 buf = bytearray(8)
732 exc = pytest.raises(ValueError, cli.recvfrom_into, buf, 1024)
733 assert str(exc.value) == "nbytes is greater than the length of the buffer"
734 conn.close()
735 serv.close()
736
737 @pytest.mark.skipif(os.name == 'nt', reason="no recvmg_into on win32")
738 def test_tcp_recvmsg_into():
739 import _socket
740 serv = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
741 serv.bind(('localhost', 0))
742 serv.listen(1)
743 cli = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
744 cli.connect(serv.getsockname())
745 fileno, addr = serv._accept()
746 conn = _socket.socket(fileno=fileno)
747 conn.send(b'Hello World!')
748 buf1 = bytearray(5)
749 buf2 = bytearray(6)
750 rettup = cli.recvmsg_into([memoryview(buf1), memoryview(buf2)])
751 nbytes, _, _, addr = rettup
752 assert nbytes == 11
753 assert buf1 == b'Hello'
754 assert buf2 == b' World'
755 conn.close()
756 cli.close()
757 serv.close()
758
759 def test_tcp_family():
760 import _socket as socket
761 cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
762 assert cli.family == socket.AF_INET
763
764 def test_tcp_missing_error_catching():
765 from _socket import socket, error
766 s = socket()
767 s.close()
768 pytest.raises(error, s.settimeout, 1) # EBADF
769 pytest.raises(error, s.setblocking, True) # EBADF
770 pytest.raises(error, s.getsockopt, 42, 84, 8) # EBADF
771
772 def test_tcp_accept_non_inheritable():
773 import _socket, os
774 serv = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
775 serv.bind(('localhost', 0))
776 serv.listen(1)
777 cli = _socket.socket()
778 cli.connect(serv.getsockname())
779 fileno, addr = serv._accept()
780 if os.name == 'nt':
781 with pytest.raises(OSError):
782 os.get_inheritable(fileno)
783 else:
784 assert os.get_inheritable(fileno) is False
785 conn = _socket.socket(fileno=fileno)
786 conn.close()
787 cli.close()
788 serv.close()
789
790 def test_tcp_recv_into_params():
791 import os
792 import _socket
793 serv = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
794 serv.bind(('localhost', 0))
795 serv.listen(1)
796 cli = _socket.socket()
797 cli.connect(serv.getsockname())
798 fileno, addr = serv._accept()
799 conn = _socket.socket(fileno=fileno)
800 conn.send(b"abcdef")
801 #
802 m = memoryview(bytearray(5))
803 pytest.raises(ValueError, cli.recv_into, m, -1)
804 pytest.raises(ValueError, cli.recv_into, m, 6)
805 cli.recv_into(m, 5)
806 assert m.tobytes() == b"abcde"
807 conn.close()
808 cli.close()
809 serv.close()
810
811 def test_tcp_bytearray_name():
812 import _socket as socket
813 if not hasattr(socket, 'AF_UNIX'):
814 pytest.skip('AF_UNIX not supported.')
815 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
816 s.bind(bytearray(b"\x00python\x00test\x00"))
817 assert s.getsockname() == b"\x00python\x00test\x00"
818
819 def test_tcp_bind_audit():
820 import _socket
821 import sys
822 events = []
823 def f(event, args):
824 events.append((event, args))
825 s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
826 sys.addaudithook(f)
827 s.bind(('localhost', 0))
828 assert len(events) == 1
829 assert events[0][0] == 'socket.bind'
830 assert events[0][1][0] is s
831 assert events[0][1][1] == ('localhost', 0)
832
833 def test_tcp_timeout_is_alias():
834 import _socket
835 assert _socket.timeout is TimeoutError
836
837
838 def test_errno():
839 from _socket import socket, AF_INET, SOCK_STREAM, error
840 import errno
841 s = socket(AF_INET, SOCK_STREAM)
842 exc = pytest.raises(error, s._accept)
843 assert isinstance(exc.value, error)
844 assert isinstance(exc.value, IOError)
845 # error is EINVAL, or WSAEINVAL on Windows
846 assert exc.value.errno == getattr(errno, 'WSAEINVAL', errno.EINVAL)
847 assert isinstance(exc.value.strerror, str)