Debian Codegraph @

rpython/rlib/test/test_rsocket.py

raw symbols SCIP
1 import pytest
2 import errno, os, sys, py
3 from rpython.rlib import rsocket
4 from rpython.rlib.rsocket import *
5 import socket as cpy_socket
6 from rpython.translator.c.test.test_genc import compile
7 from rpython.rlib.buffer import RawByteBuffer
8
9 try:
10 import fcntl
11 except ImportError:
12 fcntl = None
13
14 def setup_module(mod):
15 rsocket_startup()
16
17
18 def do_recv_from_recvmsg(socket, buffersize, flags=0):
19 msg, data, flag, address = socket.recvmsg(buffersize, flags=flags)
20 return msg
21
22 def do_recv_from_recvinto(socket, buffersize, flags=0):
23 buf = RawByteBuffer(buffersize)
24 read_bytes = socket.recvinto(buf, buffersize, flags=flags)
25 return buf.as_str()[:read_bytes]
26
27 def do_recv_from_recvmsg_into(socket, buffersize, flags=0):
28 l1 = buffersize // 2
29 l2 = buffersize - l1
30 buf1, buf2 = RawByteBuffer(l1), RawByteBuffer(l2)
31 n, data, flag, address = socket.recvmsg_into([buf1, buf2], flags=flags)
32 n1 = min(n, l1)
33 n2 = n - n1
34 return buf1.as_str()[:n1] + buf2.as_str()[:n2]
35
36
37
38 fix = [(RSocket.recv, "recv"), (do_recv_from_recvinto, "recvinto")]
39 if rsocket._c.HAVE_SENDMSG:
40 fix += [(do_recv_from_recvmsg, 'recvmsg'), (do_recv_from_recvmsg_into, "recvmsg_into")]
41 params, ids = zip(*fix)
42
43 @pytest.fixture(scope="module", params=params, ids=ids)
44 def do_recv(request):
45 return request.param
46
47
48 def test_ipv4_addr():
49 a = INETAddress("localhost", 4000)
50 assert a.get_host() == "127.0.0.1"
51 assert a.get_port() == 4000
52 a = INETAddress("", 4001)
53 assert a.get_host() == "0.0.0.0"
54 assert a.get_port() == 4001
55 a = INETAddress("<broadcast>", 47002)
56 assert a.get_host() == "255.255.255.255"
57 assert a.get_port() == 47002
58 res = repr(a)
59 assert res == "<INETAddress 255.255.255.255:47002>"
60 with pytest.raises(GAIError):
61 INETAddress("no such host exists", 47003)
62
63 @pytest.mark.skipif(getattr(rsocket, 'AF_UNIX', None) is None,
64 reason='AF_UNIX not supported.')
65 def test_unix_addr():
66 a = UNIXAddress("/tmp/socketname")
67 assert a.get_path() == "/tmp/socketname"
68
69 @pytest.mark.skipif(getattr(rsocket, 'AF_NETLINK', None) is None,
70 reason='AF_NETLINK not supported.')
71 def test_netlink_addr():
72 pid = 1
73 group_mask = 64 + 32
74 a = NETLINKAddress(pid, group_mask)
75 assert a.get_pid() == pid
76 assert a.get_groups() == group_mask
77
78 def test_gethostname():
79 s = gethostname()
80 assert isinstance(s, str)
81
82 def test_gethostbyname():
83 for host in ["localhost", "127.0.0.1"]:
84 a = gethostbyname(host)
85 assert isinstance(a, INETAddress)
86 assert a.get_host() == "127.0.0.1"
87
88 def test_gethostbyname_ex():
89 for host in ["localhost", "127.0.0.1"]:
90 name, aliases, address_list = gethostbyname_ex(host)
91 allnames = [name] + aliases
92 for n in allnames:
93 assert isinstance(n, str)
94 if sys.platform != 'win32':
95 assert host in allnames
96 for a in address_list:
97 if isinstance(a, INETAddress) and a.get_host() == "127.0.0.1":
98 break # ok
99 # no IPV6, should always return IPV4
100 else:
101 pytest.fail("could not find the localhost address in %r"
102 % (address_list,))
103
104 def test_gethostbyaddr():
105 try:
106 cpy_socket.gethostbyaddr("::1")
107 except cpy_socket.herror:
108 ipv6 = HSocketError
109 except cpy_socket.gaierror:
110 ipv6 = GAIError
111 else:
112 ipv6 = None
113 for host in ["localhost", "127.0.0.1", "::1"]:
114 if host == "::1" and ipv6:
115 with pytest.raises(ipv6):
116 gethostbyaddr(host)
117 continue
118 name, aliases, address_list = gethostbyaddr(host)
119 allnames = [name] + aliases
120 for n in allnames:
121 assert isinstance(n, str)
122 if sys.platform != 'win32':
123 assert 'localhost' in allnames or 'ip6-localhost' in allnames
124 for a in address_list:
125 if isinstance(a, INETAddress) and a.get_host() == "127.0.0.1":
126 break # ok
127 if host != '127.0.0.1': # name lookup might return IPV6
128 if isinstance(a, INET6Address) and a.get_host() == "::1":
129 break # ok
130 else:
131 pytest.fail("could not find the localhost address in %r"
132 % (address_list,))
133
134 def test_getservbyname():
135 assert getservbyname('http') == 80
136 assert getservbyname('http', 'tcp') == 80
137
138 def test_getservbyport():
139 assert getservbyport(80) == cpy_socket.getservbyport(80)
140 assert getservbyport(80, 'tcp') == cpy_socket.getservbyport(80)
141
142 def test_getprotobyname():
143 assert getprotobyname('tcp') == IPPROTO_TCP
144 assert getprotobyname('udp') == IPPROTO_UDP
145
146 @pytest.mark.skipif(sys.platform == "win32",
147 reason='No socketpair on Windows')
148 def test_socketpair(do_recv):
149 s1, s2 = socketpair()
150 s1.sendall('?')
151 buf = do_recv(s2, 100)
152 assert buf == '?'
153 count = s2.send('x'*99)
154 assert 1 <= count <= 99
155 buf = do_recv(s1, 100)
156 assert buf == 'x'*count
157 s1.close()
158 s2.close()
159
160 @pytest.mark.skipif(sys.platform == "win32",
161 reason='No socketpair on Windows')
162 def test_socketpair_inheritable():
163 for inh in [False, True]:
164 s1, s2 = socketpair(inheritable=inh)
165 assert sock_get_inheritable(s1.fd) == inh
166 assert sock_get_inheritable(s2.fd) == inh
167 s1.close()
168 s2.close()
169
170 @pytest.mark.skipif(sys.platform == "win32",
171 reason='No socketpair on Windows')
172 def test_socketpair_recvinto():
173 class Buffer:
174 def __init__(self):
175 self._p = lltype.malloc(rffi.CCHARP.TO, 100, flavor='raw',
176 track_allocation=False)
177
178 def _as_str(self, count):
179 return rffi.charpsize2str(self._p, count)
180
181 def get_raw_address(self):
182 return self._p
183
184 s1, s2 = socketpair()
185 buf = Buffer()
186 s1.sendall('?')
187 n = s2.recvinto(buf, 1)
188 assert n == 1
189 assert buf._as_str(1) == '?'
190 count = s2.send('x'*99)
191 assert 1 <= count <= 99
192 n = s1.recvinto(buf, 100)
193 assert n == count
194 assert buf._as_str(n) == 'x'*count
195 s1.close()
196 s2.close()
197
198 @pytest.mark.skipif(sys.platform == "win32",
199 reason='No socketpair on Windows')
200 def test_socketpair_recvfrom_into():
201 class Buffer:
202 def __init__(self):
203 self._p = lltype.malloc(rffi.CCHARP.TO, 100, flavor='raw',
204 track_allocation=False)
205
206 def _as_str(self, count):
207 return rffi.charpsize2str(self._p, count)
208
209 def get_raw_address(self):
210 return self._p
211
212 s1, s2 = socketpair()
213 buf = Buffer()
214 s1.sendall('?')
215 n, addr = s2.recvfrom_into(buf, 1)
216 assert n == 1
217 assert addr is None
218 assert buf._as_str(1) == '?'
219 count = s2.send('x'*99)
220 assert 1 <= count <= 99
221 n, addr = s1.recvfrom_into(buf, 100)
222 assert n == count
223 assert addr is None
224 assert buf._as_str(n) == 'x'*count
225 s1.close()
226 s2.close()
227
228
229 @py.test.mark.skipif("sys.platform == 'darwin'")
230 def test_simple_tcp(do_recv):
231 from rpython.rlib import rthread
232 sock = RSocket()
233 try_ports = [1023] + range(20000, 30000, 437)
234 for port in try_ports:
235 print 'binding to port %d:' % (port,),
236 try:
237 sock.bind(INETAddress('127.0.0.1', port))
238 print 'works'
239 break
240 except SocketError as e: # should get a "Permission denied"
241 print e
242 else:
243 raise e
244
245 addr = INETAddress('127.0.0.1', port)
246 assert addr.eq(sock.getsockname())
247 sock.listen(1)
248 s2 = RSocket(AF_INET, SOCK_STREAM)
249 s2.settimeout(1.0) # test one side with timeouts so select is used, shouldn't affect test
250 connected = [False] # thread-mutable list
251 def connecting():
252 try:
253 s2.connect(addr)
254 connected[0] = True
255 finally:
256 lock.release()
257 lock = rthread.allocate_lock()
258 lock.acquire(True)
259 rthread.start_new_thread(connecting, ())
260 print 'waiting for connection'
261 fd1, addr2 = sock.accept()
262 s1 = RSocket(fd=fd1)
263 print 'connection accepted'
264 lock.acquire(True)
265 assert connected[0]
266 print 'connecting side knows that the connection was accepted too'
267 assert addr.eq(s2.getpeername())
268 #assert addr2.eq(s2.getsockname())
269 assert addr2.eq(s1.getpeername())
270
271 s1.send('?')
272 print 'sent one character'
273 buf = do_recv(s2, 100)
274 assert buf == '?'
275 print 'received ok'
276 def sendstuff():
277 print 'sending'
278 s2.sendall('x'*50000)
279 print 'sent'
280 rthread.start_new_thread(sendstuff, ())
281 buf = ''
282 while len(buf) < 50000:
283 data = do_recv(s1, 50100)
284 print 'recv returned %d bytes' % (len(data,))
285 assert data
286 buf += data
287 assert buf == 'x'*50000
288 print 'data received ok'
289 s1.shutdown(SHUT_RDWR)
290 s1.close()
291 s2.close()
292
293 def test_simple_udp(do_recv):
294 s1 = RSocket(AF_INET, SOCK_DGRAM)
295 try_ports = [1023] + range(20000, 30000, 437)
296 for port in try_ports:
297 print 'binding to port %d:' % (port,),
298 try:
299 s1.bind(INETAddress('127.0.0.1', port))
300 print 'works'
301 break
302 except SocketError as e: # should get a "Permission denied"
303 print e
304 else:
305 raise e
306
307 addr = INETAddress('127.0.0.1', port)
308 assert addr.eq(s1.getsockname())
309 s2 = RSocket(AF_INET, SOCK_DGRAM)
310 s2.settimeout(10.0) # test one side with timeouts so select is used, shouldn't affect test
311 s2.bind(INETAddress('127.0.0.1', INADDR_ANY))
312 addr2 = s2.getsockname()
313
314 s1.sendto('?', 1, 0, addr2)
315 buf = do_recv(s2, 100)
316 assert buf == '?'
317 s2.connect(addr)
318 count = s2.send('x'*99)
319 assert 1 <= count <= 99
320 buf, addr3 = s1.recvfrom(100)
321 assert buf == 'x'*count
322 print addr2, addr3
323 assert addr2.get_port() == addr3.get_port()
324 s1.close()
325 s2.close()
326
327 @py.test.mark.skipif("sys.platform == 'darwin'")
328 def test_nonblocking(do_recv):
329 with RSocket() as sock:
330 sock.setsockopt_int(SOL_SOCKET, SO_REUSEADDR, 1)
331 sock.setblocking(False)
332 try_ports = [1023] + range(20000, 30000, 437)
333 for port in try_ports:
334 print 'binding to port %d:' % (port,),
335 try:
336 sock.bind(INETAddress('127.0.0.1', port))
337 print 'works'
338 break
339 except SocketError as e: # should get a "Permission denied"
340 print e
341 else:
342 raise e
343
344 addr = INETAddress('127.0.0.1', port)
345 assert addr.eq(sock.getsockname())
346 print("listen")
347 sock.listen(1)
348 print("listen done")
349 with pytest.raises(CSocketError) as err:
350 print("before accept")
351 try:
352 sock.accept()
353 except Exception as e:
354 print(e)
355 raise
356 print("accept raised an err")
357 assert err.value.errno in (errno.EAGAIN, errno.EWOULDBLOCK)
358
359 with RSocket(AF_INET, SOCK_STREAM) as s2:
360 s2.setblocking(False)
361 with pytest.raises(CSocketError) as err:
362 s2.connect(addr)
363 assert err.value.errno in (errno.EINPROGRESS, errno.EWOULDBLOCK)
364
365 fd1, addr2 = sock.accept()
366 with RSocket(fd=fd1) as s1:
367 s1.setblocking(False)
368 assert addr.eq(s2.getpeername())
369 assert addr2.get_port() == s2.getsockname().get_port()
370 assert addr2.eq(s1.getpeername())
371
372 err = s2.connect_ex(addr) # should now work
373 assert err in (0, errno.EISCONN)
374
375 s1.send('?')
376 import time
377 time.sleep(0.01) # Windows needs some time to transfer data
378 buf = do_recv(s2, 100)
379 assert buf == '?'
380 with pytest.raises(CSocketError) as err:
381 do_recv(s1, 5000)
382 assert err.value.errno in (errno.EAGAIN, errno.EWOULDBLOCK)
383 count = s2.send('x'*50000)
384 assert 1 <= count <= 50000
385 while count: # Recv may return less than requested
386 buf = do_recv(s1, count + 100)
387 assert len(buf) <= count
388 assert buf.count('x') == len(buf)
389 count -= len(buf)
390 # Check that everything has been read
391 with pytest.raises(CSocketError):
392 do_recv(s1, 5000)
393
394 def test_inheritable():
395 for inh in [False, True]:
396 s1 = RSocket(inheritable=inh)
397 assert sock_get_inheritable(s1.fd) == inh
398 s1.close()
399
400 def test_getaddrinfo_http():
401 lst = getaddrinfo('localhost', 'http')
402 assert isinstance(lst, list)
403 found = False
404 for family, socktype, protocol, canonname, addr in lst:
405 if (family == AF_INET and
406 socktype == SOCK_STREAM and
407 addr.get_host() == '127.0.0.1' and
408 addr.get_port() == 80):
409 found = True
410 assert found, lst
411 # The following might fail if the DNS redirects failed requests to a
412 # catch-all address (i.e. opendns).
413 with pytest.raises(GAIError) as e:
414 getaddrinfo('www.very-invalidaddress.com', None)
415 assert isinstance(e.value.get_msg(), str)
416 assert isinstance(e.value.get_msg_unicode(), unicode)
417
418 def getaddrinfo_pydotorg(i, result):
419 lst = getaddrinfo('python.org', None)
420 assert isinstance(lst, list)
421 found = False
422 for family, socktype, protocol, canonname, addr in lst:
423 if addr.get_host() in ('138.197.63.241', '104.130.43.121',
424 '23.253.135.79', '45.55.99.72',
425 '151.101.129.168', '151.101.193.168',
426 '151.101.64.223'):
427 found = True
428 elif family == AF_INET:
429 print 'pydotorg changed to', addr.get_host()
430 result[i] += found
431
432 def test_getaddrinfo_pydotorg():
433 result = [0]
434 getaddrinfo_pydotorg(0, result)
435 assert result[0] == 1
436
437
438 def test_getaddrinfo_no_reverse_lookup():
439 # It seems that getaddrinfo never runs a reverse lookup on Linux.
440 # Python2.3 on Windows returns the hostname.
441 lst = getaddrinfo('82.94.164.162', None, flags=AI_NUMERICHOST)
442 assert isinstance(lst, list)
443 found = False
444 print lst
445 for family, socktype, protocol, canonname, addr in lst:
446 assert 'python.org' not in canonname
447 if addr.get_host() == '82.94.164.162':
448 found = True
449 assert found, lst
450
451 def test_getaddrinfo_osx_crash():
452 # see CPython issue17269
453 for port in [None, '0', '00']:
454 getaddrinfo('localhost', port, 0, 0, 0, AI_NUMERICSERV)
455
456 def test_connect_ex():
457 s = RSocket()
458 err = s.connect_ex(INETAddress('0.0.0.0', 0)) # should not work
459 assert err in (errno.ECONNREFUSED, errno.EADDRNOTAVAIL)
460 s.close()
461
462 @py.test.mark.skipif("sys.platform == 'darwin'")
463 def test_connect_with_timeout_fail():
464 s = RSocket()
465 s.settimeout(0.1)
466 with pytest.raises(SocketTimeout):
467 s.connect(INETAddress('172.30.172.30', 12345))
468 s.close()
469
470 @py.test.mark.skipif("sys.platform == 'darwin'")
471 def test_connect_with_timeout_succeed():
472 s = RSocket()
473 s.settimeout(10.0)
474 s.connect(INETAddress('python.org', 80))
475 s.close()
476
477 @py.test.mark.skipif("sys.platform == 'darwin'")
478 def test_connect_with_default_timeout_fail():
479 rsocket.setdefaulttimeout(0.1)
480 s = RSocket()
481 rsocket.setdefaulttimeout(None)
482 assert s.gettimeout() == 0.1
483 with pytest.raises(SocketTimeout):
484 s.connect(INETAddress('172.30.172.30', 12345))
485 s.close()
486
487 def test_getsetsockopt():
488 import struct
489 assert struct.calcsize("i") == rffi.sizeof(rffi.INT)
490 # A socket sould start with reuse == 0
491 s = RSocket(AF_INET, SOCK_STREAM)
492 reuse = s.getsockopt_int(SOL_SOCKET, SO_REUSEADDR)
493 assert reuse == 0
494 s.setsockopt_int(SOL_SOCKET, SO_REUSEADDR, 1)
495 reuse = s.getsockopt_int(SOL_SOCKET, SO_REUSEADDR)
496 assert reuse != 0
497 # Test string case
498 s = RSocket(AF_INET, SOCK_STREAM)
499 reusestr = s.getsockopt(SOL_SOCKET, SO_REUSEADDR, rffi.sizeof(rffi.INT))
500 value, = struct.unpack("i", reusestr)
501 assert value == 0
502 optstr = struct.pack("i", 1)
503 s.setsockopt(SOL_SOCKET, SO_REUSEADDR, optstr)
504 reusestr = s.getsockopt(SOL_SOCKET, SO_REUSEADDR, rffi.sizeof(rffi.INT))
505 value, = struct.unpack("i", reusestr)
506 assert value != 0
507
508 def test_getsetsockopt_global():
509 # A socket sould start with reuse == 0
510 s = RSocket(AF_INET, SOCK_STREAM)
511 fd = s.fd
512 reuse = getsockopt_int(fd, SOL_SOCKET, SO_REUSEADDR)
513 assert reuse == 0
514 s.setsockopt_int(SOL_SOCKET, SO_REUSEADDR, 1)
515 reuse = getsockopt_int(fd, SOL_SOCKET, SO_REUSEADDR)
516 assert reuse != 0
517
518
519 @pytest.mark.skipif(sys.platform == 'win32', reason='requires bound socket')
520 def test_get_socket_family():
521 s = RSocket(AF_INET, SOCK_STREAM)
522 fd = s.fd
523 assert get_socket_family(fd) == AF_INET
524
525 if getattr(rsocket, 'AF_UNIX', None) is not None:
526 s = RSocket(AF_UNIX)
527 fd = s.fd
528 assert get_socket_family(fd) == AF_UNIX
529
530 def test_dup():
531 s = RSocket(AF_INET, SOCK_STREAM)
532 try:
533 s.bind(INETAddress('localhost', 50007))
534 if sys.platform == "win32":
535 assert not hasattr(s, 'dup')
536 return
537 s2 = s.dup()
538 try:
539 assert s.fd != s2.fd
540 assert s.getsockname().eq(s2.getsockname())
541 finally:
542 s2.close()
543 finally:
544 s.close()
545
546 def test_c_dup():
547 # rsocket.dup() duplicates fd, it also works on Windows
548 # (but only on socket handles!)
549 s = RSocket(AF_INET, SOCK_STREAM)
550 try:
551 s.bind(INETAddress('localhost', 50007))
552 s2 = RSocket(fd=dup(s.fd))
553 try:
554 assert s.fd != s2.fd
555 assert s.getsockname().eq(s2.getsockname())
556 finally:
557 s2.close()
558 finally:
559 s.close()
560
561 def test_inet_aton():
562 assert inet_aton('1.2.3.4') == '\x01\x02\x03\x04'
563 assert inet_aton('127.0.0.1') == '\x7f\x00\x00\x01'
564 tests = ["127.0.0.256", "127.0.0.255555555555555555", "127.2b.0.0",
565 "127.2.0.0.1", "127.2.0."]
566 for ip in tests:
567 with pytest.raises(SocketError):
568 inet_aton(ip)
569
570 # Windows 2000: missing numbers are replaced by 0
571 for ip, aton in [("11..22.33", '\x0b\x00\x16\x21'),
572 (".11.22.33", '\x00\x0b\x16\x21')]:
573 try:
574 assert inet_aton(ip) == aton
575 except SocketError:
576 pass
577
578 def test_inet_ntoa():
579 assert inet_ntoa('\x01\x02\x03\x04') == '1.2.3.4'
580
581 @pytest.mark.skipif(not hasattr(rsocket, 'inet_pton'), reason="no inet_pton()")
582 def test_inet_pton():
583 assert inet_pton(AF_INET, '1.2.3.5') == '\x01\x02\x03\x05'
584 with pytest.raises(SocketError):
585 inet_pton(AF_INET, '127.0.0.256')
586
587 @pytest.mark.skipif(not hasattr(rsocket, 'inet_ntop'), reason="no inet_ntop()")
588 def test_inet_ntop():
589 assert inet_ntop(AF_INET, '\x01\x02\x03\x05') == '1.2.3.5'
590
591 @pytest.mark.skipif(getattr(rsocket, 'AF_UNIX', None) is None,
592 reason='AF_UNIX not supported.')
593 def test_unix_socket_connect(tmpdir, do_recv):
594 prev_dir = tmpdir.chdir() # workaround for limited path length
595 try:
596 do_test_unix_socket_connect(do_recv)
597 finally:
598 prev_dir.chdir()
599
600 def do_test_unix_socket_connect(do_recv):
601 sockpath = './test_unix_socket_connect'
602 a = UNIXAddress(sockpath)
603
604 serversock = RSocket(AF_UNIX)
605 serversock.bind(a)
606 serversock.listen(1)
607
608 clientsock = RSocket(AF_UNIX)
609 clientsock.connect(a)
610 fd, addr = serversock.accept()
611 s = RSocket(AF_UNIX, fd=fd)
612
613 s.send('X')
614 data = do_recv(clientsock, 100)
615 assert data == 'X'
616 clientsock.send('Y')
617 data = do_recv(s, 100)
618 assert data == 'Y'
619
620 clientsock.close()
621 s.close()
622
623 class TestTCP:
624 PORT = 50007
625 HOST = 'localhost'
626
627 def setup_method(self, method):
628 self.serv = RSocket(AF_INET, SOCK_STREAM)
629 self.serv.bind(INETAddress(self.HOST, self.PORT))
630 self.serv.listen(1)
631
632 def teardown_method(self, method):
633 self.serv.close()
634 self.serv = None
635
636 def test_timeout(self):
637 self.serv.settimeout(1.0)
638 with pytest.raises(SocketTimeout):
639 self.serv.accept()
640
641 @py.test.mark.skipif("sys.platform == 'darwin'")
642 def test_timeout_zero(self):
643 self.serv.settimeout(0.0)
644 with pytest.raises(SocketError):
645 foo = self.serv.accept()
646
647 def _test_cond_include(cond):
648 # Test that _rsocket_rffi is importable even on platforms where
649 # AF_PACKET or AF_NETLINK is not defined.
650 import re
651 from rpython.rlib import _rsocket_rffi
652 srcfile = _rsocket_rffi.__file__
653 if srcfile.lower().endswith('c') or srcfile.lower().endswith('o'):
654 srcfile = srcfile[:-1] # .pyc => .py
655 assert srcfile.lower().endswith('.py')
656 sourcelines = open(srcfile, 'rb').read().splitlines()
657 found = False
658 for i, line in enumerate(sourcelines):
659 line2 = re.sub(r"(\s*COND_HEADER\s*=)",
660 r"\1'#undef %s\\n'+" % cond,
661 line)
662 if line2 != line:
663 found = True
664 sourcelines[i] = line2
665 assert found
666 d = {}
667 sourcelines.append('')
668 exec('\n'.join(sourcelines), d)
669
670 def test_no_AF_PACKET():
671 _test_cond_include('AF_PACKET')
672
673 def test_no_AF_NETLINK():
674 _test_cond_include('AF_NETLINK')
675
676 @pytest.mark.xfail(reason="hits non-thread-safe issues with ll2ctypes")
677 def test_thread_safe_gethostbyaddr():
678 import threading
679 nthreads = 10
680 ip = '8.8.8.8'
681 domain = gethostbyaddr(ip)[0]
682 result = [0] * nthreads
683 threads = [None] * nthreads
684 lock = threading.Lock()
685 def lookup_addr(ip, i):
686 name, aliases, address_list = gethostbyaddr(ip, lock)
687 if name == domain:
688 result[i] += 1
689 for i in range(nthreads):
690 threads[i] = threading.Thread(target = lookup_addr, args=[ip, i])
691 threads[i].start()
692 for i in range(nthreads):
693 threads[i].join()
694 assert sum(result) == nthreads
695
696 @pytest.mark.xfail(reason="hits non-thread-safe issues with ll2ctypes")
697 def test_thread_safe_gethostbyname_ex():
698 import threading
699 nthreads = 10
700 domain = 'google.com'
701 result = [0] * nthreads
702 threads = [None] * nthreads
703 lock = threading.Lock()
704 def lookup_name(i):
705 name, aliases, address_list = gethostbyname_ex(domain, lock)
706 if name == domain:
707 result[i] += 1
708 for i in range(nthreads):
709 threads[i] = threading.Thread(target = lookup_name, args=[i])
710 threads[i].start()
711 for i in range(nthreads):
712 threads[i].join()
713 assert sum(result) == nthreads
714
715 @pytest.mark.xfail(reason="hits non-thread-safe issues with ll2ctypes")
716 def test_getaddrinfo_pydotorg_threadsafe():
717 import threading
718 nthreads = 10
719 result = [0] * nthreads
720 threads = [None] * nthreads
721 for i in range(nthreads):
722 threads[i] = threading.Thread(target = getaddrinfo_pydotorg, args=[i, result])
723 threads[i].start()
724 for i in range(nthreads):
725 threads[i].join()
726 assert sum(result) == nthreads
727
728 def test_translate_netdb_lock():
729 def f():
730 rsocket_startup()
731 gethostbyaddr("localhost")
732 return 0
733 fc = compile(f, [])
734 assert fc() == 0
735
736 def test_translate_netdb_lock_thread():
737 def f():
738 rsocket_startup()
739 gethostbyaddr("localhost")
740 return 0
741 fc = compile(f, [], thread=True)
742 assert fc() == 0
743
744 def test_socket_saves_errno(do_recv):
745 # ensure errno is set to a known value...
746 unconnected_sock = RSocket()
747 with pytest.raises(CSocketError) as e:
748 do_recv(unconnected_sock, 1024)
749 # ...which is ENOTCONN
750 assert e.value.errno == errno.ENOTCONN
751
752 with pytest.raises(CSocketError) as e:
753 RSocket(family=AF_INET, type=SOCK_STREAM, proto=SOL_UDP)
754 assert e.value.errno in (errno.EPROTOTYPE, errno.EPROTONOSUPPORT)
755
756 @pytest.mark.skipif(fcntl is None, reason="requires fcntl")
757 @py.test.mark.skipif("sys.platform == 'darwin'")
758 def test_socket_init_non_blocking():
759 import fcntl, os
760 s = RSocket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK)
761 assert s.type == SOCK_STREAM
762 assert s.gettimeout() == 0.0
763 assert fcntl.fcntl(s.fd, fcntl.F_GETFL, os.O_NONBLOCK) & os.O_NONBLOCK
764
765 # It is a bad idea to change running system's hostname, so do it only
766 # if we can reasonably assume the request will be rejected, i.e. we don't
767 # have superuser privileges.
768 @pytest.mark.skipif(sys.platform == "win32",
769 reason='No sethostname on Windows')
770 @pytest.mark.skipif(not hasattr(os, 'geteuid') or os.geteuid() == 0,
771 reason='Running as superuser is not supported.')
772 def test_sethostname():
773 # just in case it worked anyway, use the old hostname
774 s = gethostname()
775 with pytest.raises(CSocketError) as e:
776 sethostname(s)
777 assert e.value.errno == errno.EPERM
778
779 @pytest.mark.skipif(sys.platform != "linux",
780 reason='this behaviour of MSG_TRUNC is linux specific')
781 def test_msg_trunc_weirdness_linux():
782 import socket
783 (a, b) = socketpair(rsocket.AF_UNIX, rsocket.SOCK_DGRAM)
784 a.send(b'abcdefgh')
785 result = b.recv(2, socket.MSG_TRUNC)
786 assert result == b'ab'
787
788 def test_if_nameindex():
789 nameindex = rsocket.if_nameindex()
790 assert len(nameindex) > 0