PageRenderTime 61ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/rpython/rlib/test/test_rsocket.py

https://bitbucket.org/pjenvey/pypy-mq
Python | 707 lines | 704 code | 3 blank | 0 comment | 3 complexity | f927f695fb97c15b04425a187af481c9 MD5 | raw file
Possible License(s): Apache-2.0, AGPL-3.0, BSD-3-Clause
  1. import py, errno, sys
  2. from rpython.rlib import rsocket
  3. from rpython.rlib.rsocket import *
  4. import socket as cpy_socket
  5. from rpython.translator.c.test.test_genc import compile
  6. def setup_module(mod):
  7. rsocket_startup()
  8. def test_ipv4_addr():
  9. a = INETAddress("localhost", 4000)
  10. assert a.get_host() == "127.0.0.1"
  11. assert a.get_port() == 4000
  12. a = INETAddress("", 4001)
  13. assert a.get_host() == "0.0.0.0"
  14. assert a.get_port() == 4001
  15. a = INETAddress("<broadcast>", 47002)
  16. assert a.get_host() == "255.255.255.255"
  17. assert a.get_port() == 47002
  18. py.test.raises(GAIError, INETAddress, "no such host exists", 47003)
  19. res = repr(a)
  20. assert res == "<INETAddress 255.255.255.255:47002>"
  21. def test_unix_addr():
  22. if getattr(rsocket, 'AF_UNIX', None) is None:
  23. py.test.skip('AF_UNIX not supported.')
  24. a = UNIXAddress("/tmp/socketname")
  25. assert a.get_path() == "/tmp/socketname"
  26. def test_netlink_addr():
  27. if getattr(rsocket, 'AF_NETLINK', None) is None:
  28. py.test.skip('AF_NETLINK not supported.')
  29. pid = 1
  30. group_mask = 64 + 32
  31. a = NETLINKAddress(pid, group_mask)
  32. assert a.get_pid() == pid
  33. assert a.get_groups() == group_mask
  34. def test_gethostname():
  35. s = gethostname()
  36. assert isinstance(s, str)
  37. def test_gethostbyname():
  38. for host in ["localhost", "127.0.0.1"]:
  39. a = gethostbyname(host)
  40. assert isinstance(a, INETAddress)
  41. assert a.get_host() == "127.0.0.1"
  42. def test_gethostbyname_ex():
  43. for host in ["localhost", "127.0.0.1"]:
  44. name, aliases, address_list = gethostbyname_ex(host)
  45. allnames = [name] + aliases
  46. for n in allnames:
  47. assert isinstance(n, str)
  48. if sys.platform != 'win32':
  49. assert host in allnames
  50. for a in address_list:
  51. if isinstance(a, INETAddress) and a.get_host() == "127.0.0.1":
  52. break # ok
  53. # no IPV6, should always return IPV4
  54. else:
  55. py.test.fail("could not find the localhost address in %r"
  56. % (address_list,))
  57. def test_gethostbyaddr():
  58. try:
  59. cpy_socket.gethostbyaddr("::1")
  60. except cpy_socket.herror:
  61. ipv6 = HSocketError
  62. except cpy_socket.gaierror:
  63. ipv6 = GAIError
  64. else:
  65. ipv6 = None
  66. for host in ["localhost", "127.0.0.1", "::1"]:
  67. if host == "::1" and ipv6:
  68. with py.test.raises(ipv6):
  69. gethostbyaddr(host)
  70. continue
  71. name, aliases, address_list = gethostbyaddr(host)
  72. allnames = [name] + aliases
  73. for n in allnames:
  74. assert isinstance(n, str)
  75. if sys.platform != 'win32':
  76. assert 'localhost' in allnames or 'ip6-localhost' in allnames
  77. for a in address_list:
  78. if isinstance(a, INETAddress) and a.get_host() == "127.0.0.1":
  79. break # ok
  80. if host != '127.0.0.1': # name lookup might return IPV6
  81. if isinstance(a, INET6Address) and a.get_host() == "::1":
  82. break # ok
  83. else:
  84. py.test.fail("could not find the localhost address in %r"
  85. % (address_list,))
  86. def test_getservbyname():
  87. assert getservbyname('http') == 80
  88. assert getservbyname('http', 'tcp') == 80
  89. def test_getservbyport():
  90. assert getservbyport(80) == cpy_socket.getservbyport(80)
  91. assert getservbyport(80, 'tcp') == cpy_socket.getservbyport(80)
  92. def test_getprotobyname():
  93. assert getprotobyname('tcp') == IPPROTO_TCP
  94. assert getprotobyname('udp') == IPPROTO_UDP
  95. def test_socketpair():
  96. if sys.platform == "win32":
  97. py.test.skip('No socketpair on Windows')
  98. s1, s2 = socketpair()
  99. s1.sendall('?')
  100. buf = s2.recv(100)
  101. assert buf == '?'
  102. count = s2.send('x'*99)
  103. assert 1 <= count <= 99
  104. buf = s1.recv(100)
  105. assert buf == 'x'*count
  106. s1.close()
  107. s2.close()
  108. def test_socketpair_inheritable():
  109. if sys.platform == "win32":
  110. py.test.skip('No socketpair on Windows')
  111. for inh in [False, True]:
  112. s1, s2 = socketpair(inheritable=inh)
  113. assert rposix.get_inheritable(s1.fd) == inh
  114. assert rposix.get_inheritable(s2.fd) == inh
  115. s1.close()
  116. s2.close()
  117. def test_socketpair_recvinto_1():
  118. class Buffer:
  119. def setslice(self, start, string):
  120. self.x = string
  121. def get_raw_address(self):
  122. raise ValueError
  123. if sys.platform == "win32":
  124. py.test.skip('No socketpair on Windows')
  125. s1, s2 = socketpair()
  126. buf = Buffer()
  127. s1.sendall('?')
  128. n = s2.recvinto(buf, 1)
  129. assert n == 1
  130. assert buf.x == '?'
  131. count = s2.send('x'*99)
  132. assert 1 <= count <= 99
  133. n = s1.recvinto(buf, 100)
  134. assert n == count
  135. assert buf.x == 'x'*count
  136. s1.close()
  137. s2.close()
  138. def test_socketpair_recvinto_2():
  139. class Buffer:
  140. def __init__(self):
  141. self._p = lltype.malloc(rffi.CCHARP.TO, 100, flavor='raw',
  142. track_allocation=False)
  143. def _as_str(self, count):
  144. return rffi.charpsize2str(self._p, count)
  145. def get_raw_address(self):
  146. return self._p
  147. if sys.platform == "win32":
  148. py.test.skip('No socketpair on Windows')
  149. s1, s2 = socketpair()
  150. buf = Buffer()
  151. s1.sendall('?')
  152. n = s2.recvinto(buf, 1)
  153. assert n == 1
  154. assert buf._as_str(1) == '?'
  155. count = s2.send('x'*99)
  156. assert 1 <= count <= 99
  157. n = s1.recvinto(buf, 100)
  158. assert n == count
  159. assert buf._as_str(n) == 'x'*count
  160. s1.close()
  161. s2.close()
  162. def test_socketpair_recvfrom_into_1():
  163. class Buffer:
  164. def setslice(self, start, string):
  165. self.x = string
  166. def get_raw_address(self):
  167. raise ValueError
  168. if sys.platform == "win32":
  169. py.test.skip('No socketpair on Windows')
  170. s1, s2 = socketpair()
  171. buf = Buffer()
  172. s1.sendall('?')
  173. n, addr = s2.recvfrom_into(buf, 1)
  174. assert n == 1
  175. assert addr is None
  176. assert buf.x == '?'
  177. count = s2.send('x'*99)
  178. assert 1 <= count <= 99
  179. n, addr = s1.recvfrom_into(buf, 100)
  180. assert n == count
  181. assert addr is None
  182. assert buf.x == 'x'*count
  183. s1.close()
  184. s2.close()
  185. def test_socketpair_recvfrom_into_2():
  186. class Buffer:
  187. def __init__(self):
  188. self._p = lltype.malloc(rffi.CCHARP.TO, 100, flavor='raw',
  189. track_allocation=False)
  190. def _as_str(self, count):
  191. return rffi.charpsize2str(self._p, count)
  192. def get_raw_address(self):
  193. return self._p
  194. if sys.platform == "win32":
  195. py.test.skip('No socketpair on Windows')
  196. s1, s2 = socketpair()
  197. buf = Buffer()
  198. s1.sendall('?')
  199. n, addr = s2.recvfrom_into(buf, 1)
  200. assert n == 1
  201. assert addr is None
  202. assert buf._as_str(1) == '?'
  203. count = s2.send('x'*99)
  204. assert 1 <= count <= 99
  205. n, addr = s1.recvfrom_into(buf, 100)
  206. assert n == count
  207. assert addr is None
  208. assert buf._as_str(n) == 'x'*count
  209. s1.close()
  210. s2.close()
  211. def test_simple_tcp():
  212. from rpython.rlib import rthread
  213. sock = RSocket()
  214. try_ports = [1023] + range(20000, 30000, 437)
  215. for port in try_ports:
  216. print 'binding to port %d:' % (port,),
  217. try:
  218. sock.bind(INETAddress('127.0.0.1', port))
  219. print 'works'
  220. break
  221. except SocketError as e: # should get a "Permission denied"
  222. print e
  223. else:
  224. raise e
  225. addr = INETAddress('127.0.0.1', port)
  226. assert addr.eq(sock.getsockname())
  227. sock.listen(1)
  228. s2 = RSocket(AF_INET, SOCK_STREAM)
  229. s2.settimeout(10.0) # test one side with timeouts so select is used, shouldn't affect test
  230. connected = [False] #thread-mutable list
  231. def connecting():
  232. try:
  233. s2.connect(addr)
  234. connected[0] = True
  235. finally:
  236. lock.release()
  237. lock = rthread.allocate_lock()
  238. lock.acquire(True)
  239. rthread.start_new_thread(connecting, ())
  240. print 'waiting for connection'
  241. fd1, addr2 = sock.accept()
  242. s1 = RSocket(fd=fd1)
  243. print 'connection accepted'
  244. lock.acquire(True)
  245. assert connected[0]
  246. print 'connecting side knows that the connection was accepted too'
  247. assert addr.eq(s2.getpeername())
  248. #assert addr2.eq(s2.getsockname())
  249. assert addr2.eq(s1.getpeername())
  250. s1.send('?')
  251. print 'sent one character'
  252. buf = s2.recv(100)
  253. assert buf == '?'
  254. print 'received ok'
  255. def sendstuff():
  256. s2.sendall('x'*50000)
  257. rthread.start_new_thread(sendstuff, ())
  258. buf = ''
  259. while len(buf) < 50000:
  260. data = s1.recv(50100)
  261. print 'recv returned %d bytes' % (len(data,))
  262. assert data
  263. buf += data
  264. assert buf == 'x'*50000
  265. print 'data received ok'
  266. s1.shutdown(SHUT_RDWR)
  267. s1.close()
  268. s2.close()
  269. def test_simple_udp():
  270. s1 = RSocket(AF_INET, SOCK_DGRAM)
  271. try_ports = [1023] + range(20000, 30000, 437)
  272. for port in try_ports:
  273. print 'binding to port %d:' % (port,),
  274. try:
  275. s1.bind(INETAddress('127.0.0.1', port))
  276. print 'works'
  277. break
  278. except SocketError as e: # should get a "Permission denied"
  279. print e
  280. else:
  281. raise e
  282. addr = INETAddress('127.0.0.1', port)
  283. assert addr.eq(s1.getsockname())
  284. s2 = RSocket(AF_INET, SOCK_DGRAM)
  285. s2.settimeout(10.0) # test one side with timeouts so select is used, shouldn't affect test
  286. s2.bind(INETAddress('127.0.0.1', INADDR_ANY))
  287. addr2 = s2.getsockname()
  288. s1.sendto('?', 0, addr2)
  289. buf = s2.recv(100)
  290. assert buf == '?'
  291. s2.connect(addr)
  292. count = s2.send('x'*99)
  293. assert 1 <= count <= 99
  294. buf, addr3 = s1.recvfrom(100)
  295. assert buf == 'x'*count
  296. print addr2, addr3
  297. assert addr2.get_port() == addr3.get_port()
  298. s1.close()
  299. s2.close()
  300. def test_nonblocking():
  301. sock = RSocket()
  302. sock.setblocking(False)
  303. try_ports = [1023] + range(20000, 30000, 437)
  304. for port in try_ports:
  305. print 'binding to port %d:' % (port,),
  306. try:
  307. sock.bind(INETAddress('127.0.0.1', port))
  308. print 'works'
  309. break
  310. except SocketError as e: # should get a "Permission denied"
  311. print e
  312. else:
  313. raise e
  314. addr = INETAddress('127.0.0.1', port)
  315. assert addr.eq(sock.getsockname())
  316. sock.listen(1)
  317. err = py.test.raises(CSocketError, sock.accept)
  318. assert err.value.errno in (errno.EAGAIN, errno.EWOULDBLOCK)
  319. s2 = RSocket(AF_INET, SOCK_STREAM)
  320. s2.setblocking(False)
  321. err = py.test.raises(CSocketError, s2.connect, addr)
  322. assert err.value.errno in (errno.EINPROGRESS, errno.EWOULDBLOCK)
  323. fd1, addr2 = sock.accept()
  324. s1 = RSocket(fd=fd1)
  325. s1.setblocking(False)
  326. assert addr.eq(s2.getpeername())
  327. assert addr2.get_port() == s2.getsockname().get_port()
  328. assert addr2.eq(s1.getpeername())
  329. err = s2.connect_ex(addr) # should now work
  330. assert err in (0, errno.EISCONN)
  331. s1.send('?')
  332. import time
  333. time.sleep(0.01) # Windows needs some time to transfer data
  334. buf = s2.recv(100)
  335. assert buf == '?'
  336. err = py.test.raises(CSocketError, s1.recv, 5000)
  337. assert err.value.errno in (errno.EAGAIN, errno.EWOULDBLOCK)
  338. count = s2.send('x'*50000)
  339. assert 1 <= count <= 50000
  340. while count: # Recv may return less than requested
  341. buf = s1.recv(count + 100)
  342. assert len(buf) <= count
  343. assert buf.count('x') == len(buf)
  344. count -= len(buf)
  345. # Check that everything has been read
  346. err = py.test.raises(CSocketError, s1.recv, 5000)
  347. s1.close()
  348. s2.close()
  349. def test_inheritable():
  350. for inh in [False, True]:
  351. s1 = RSocket(inheritable=inh)
  352. assert rposix.get_inheritable(s1.fd) == inh
  353. s1.close()
  354. def test_getaddrinfo_http():
  355. lst = getaddrinfo('localhost', 'http')
  356. assert isinstance(lst, list)
  357. found = False
  358. for family, socktype, protocol, canonname, addr in lst:
  359. if (family == AF_INET and
  360. socktype == SOCK_STREAM and
  361. addr.get_host() == '127.0.0.1' and
  362. addr.get_port() == 80):
  363. found = True
  364. assert found, lst
  365. # The following might fail if the DNS redirects failed requests to a
  366. # catch-all address (i.e. opendns).
  367. e = py.test.raises(GAIError, getaddrinfo, 'www.very-invalidaddress.com', None)
  368. assert isinstance(e.value.get_msg(), str)
  369. def getaddrinfo_pydotorg(i, result):
  370. lst = getaddrinfo('python.org', None)
  371. assert isinstance(lst, list)
  372. found = False
  373. for family, socktype, protocol, canonname, addr in lst:
  374. if addr.get_host() in ('104.130.43.121', '23.253.135.79'):
  375. found = True
  376. elif family == AF_INET:
  377. print 'pydotorg changed to', addr.get_host()
  378. result[i] += found
  379. def test_getaddrinfo_pydotorg():
  380. result = [0,]
  381. getaddrinfo_pydotorg(0, result)
  382. assert result[0] == 1
  383. def test_getaddrinfo_no_reverse_lookup():
  384. # It seems that getaddrinfo never runs a reverse lookup on Linux.
  385. # Python2.3 on Windows returns the hostname.
  386. lst = getaddrinfo('82.94.164.162', None, flags=AI_NUMERICHOST)
  387. assert isinstance(lst, list)
  388. found = False
  389. print lst
  390. for family, socktype, protocol, canonname, addr in lst:
  391. assert 'python.org' not in canonname
  392. if addr.get_host() == '82.94.164.162':
  393. found = True
  394. assert found, lst
  395. def test_getaddrinfo_osx_crash():
  396. # see CPython issue17269
  397. for port in [None, '0', '00']:
  398. getaddrinfo('localhost', port, 0, 0, 0, AI_NUMERICSERV)
  399. def test_connect_ex():
  400. s = RSocket()
  401. err = s.connect_ex(INETAddress('0.0.0.0', 0)) # should not work
  402. assert err in (errno.ECONNREFUSED, errno.EADDRNOTAVAIL)
  403. s.close()
  404. def test_connect_with_timeout_fail():
  405. s = RSocket()
  406. s.settimeout(0.1)
  407. with py.test.raises(SocketTimeout):
  408. s.connect(INETAddress('172.30.172.30', 12345))
  409. s.close()
  410. def test_connect_with_timeout_succeed():
  411. s = RSocket()
  412. s.settimeout(10.0)
  413. s.connect(INETAddress('python.org', 80))
  414. s.close()
  415. def test_getsetsockopt():
  416. import struct
  417. assert struct.calcsize("i") == rffi.sizeof(rffi.INT)
  418. # A socket sould start with reuse == 0
  419. s = RSocket(AF_INET, SOCK_STREAM)
  420. reuse = s.getsockopt_int(SOL_SOCKET, SO_REUSEADDR)
  421. assert reuse == 0
  422. s.setsockopt_int(SOL_SOCKET, SO_REUSEADDR, 1)
  423. reuse = s.getsockopt_int(SOL_SOCKET, SO_REUSEADDR)
  424. assert reuse != 0
  425. # Test string case
  426. s = RSocket(AF_INET, SOCK_STREAM)
  427. reusestr = s.getsockopt(SOL_SOCKET, SO_REUSEADDR, rffi.sizeof(rffi.INT))
  428. value, = struct.unpack("i", reusestr)
  429. assert value == 0
  430. optstr = struct.pack("i", 1)
  431. s.setsockopt(SOL_SOCKET, SO_REUSEADDR, optstr)
  432. reusestr = s.getsockopt(SOL_SOCKET, SO_REUSEADDR, rffi.sizeof(rffi.INT))
  433. value, = struct.unpack("i", reusestr)
  434. assert value != 0
  435. def test_dup():
  436. s = RSocket(AF_INET, SOCK_STREAM)
  437. try:
  438. s.bind(INETAddress('localhost', 50007))
  439. if sys.platform == "win32":
  440. assert not hasattr(s, 'dup')
  441. return
  442. s2 = s.dup()
  443. try:
  444. assert s.fd != s2.fd
  445. assert s.getsockname().eq(s2.getsockname())
  446. finally:
  447. s2.close()
  448. finally:
  449. s.close()
  450. def test_c_dup():
  451. # rsocket.dup() duplicates fd, it also works on Windows
  452. # (but only on socket handles!)
  453. s = RSocket(AF_INET, SOCK_STREAM)
  454. try:
  455. s.bind(INETAddress('localhost', 50007))
  456. s2 = RSocket(fd=dup(s.fd))
  457. try:
  458. assert s.fd != s2.fd
  459. assert s.getsockname().eq(s2.getsockname())
  460. finally:
  461. s2.close()
  462. finally:
  463. s.close()
  464. def test_inet_aton():
  465. assert inet_aton('1.2.3.4') == '\x01\x02\x03\x04'
  466. assert inet_aton('127.0.0.1') == '\x7f\x00\x00\x01'
  467. tests = ["127.0.0.256", "127.0.0.255555555555555555", "127.2b.0.0",
  468. "127.2.0.0.1", "127.2.0."]
  469. for ip in tests:
  470. py.test.raises(SocketError, inet_aton, ip)
  471. # Windows 2000: missing numbers are replaced by 0
  472. for ip, aton in [("11..22.33", '\x0b\x00\x16\x21'),
  473. (".11.22.33", '\x00\x0b\x16\x21')]:
  474. try:
  475. assert inet_aton(ip) == aton
  476. except SocketError:
  477. pass
  478. def test_inet_ntoa():
  479. assert inet_ntoa('\x01\x02\x03\x04') == '1.2.3.4'
  480. def test_inet_pton():
  481. if not hasattr(rsocket, 'inet_pton'):
  482. py.test.skip("no inet_pton()")
  483. assert inet_pton(AF_INET, '1.2.3.5') == '\x01\x02\x03\x05'
  484. py.test.raises(SocketError, inet_pton, AF_INET, '127.0.0.256')
  485. def test_inet_ntop():
  486. if not hasattr(rsocket, 'inet_ntop'):
  487. py.test.skip("no inet_ntop()")
  488. assert inet_ntop(AF_INET, '\x01\x02\x03\x05') == '1.2.3.5'
  489. def test_unix_socket_connect():
  490. if getattr(rsocket, 'AF_UNIX', None) is None:
  491. py.test.skip('AF_UNIX not supported.')
  492. from rpython.tool.udir import udir
  493. sockpath = str(udir.join('test_unix_socket_connect'))
  494. a = UNIXAddress(sockpath)
  495. serversock = RSocket(AF_UNIX)
  496. serversock.bind(a)
  497. serversock.listen(1)
  498. clientsock = RSocket(AF_UNIX)
  499. clientsock.connect(a)
  500. fd, addr = serversock.accept()
  501. s = RSocket(AF_UNIX, fd=fd)
  502. s.send('X')
  503. data = clientsock.recv(100)
  504. assert data == 'X'
  505. clientsock.send('Y')
  506. data = s.recv(100)
  507. assert data == 'Y'
  508. clientsock.close()
  509. s.close()
  510. class TestTCP:
  511. PORT = 50007
  512. HOST = 'localhost'
  513. def setup_method(self, method):
  514. self.serv = RSocket(AF_INET, SOCK_STREAM)
  515. self.serv.bind(INETAddress(self.HOST, self.PORT))
  516. self.serv.listen(1)
  517. def teardown_method(self, method):
  518. self.serv.close()
  519. self.serv = None
  520. def test_timeout(self):
  521. def raise_timeout():
  522. self.serv.settimeout(1.0)
  523. self.serv.accept()
  524. py.test.raises(SocketTimeout, raise_timeout)
  525. def test_timeout_zero(self):
  526. def raise_error():
  527. self.serv.settimeout(0.0)
  528. foo = self.serv.accept()
  529. py.test.raises(SocketError, raise_error)
  530. def _test_cond_include(cond):
  531. # Test that _rsocket_rffi is importable even on platforms where
  532. # AF_PACKET or AF_NETLINK is not defined.
  533. import re
  534. from rpython.rlib import _rsocket_rffi
  535. srcfile = _rsocket_rffi.__file__
  536. if srcfile.lower().endswith('c') or srcfile.lower().endswith('o'):
  537. srcfile = srcfile[:-1] # .pyc => .py
  538. assert srcfile.lower().endswith('.py')
  539. sourcelines = open(srcfile, 'rb').read().splitlines()
  540. found = False
  541. for i, line in enumerate(sourcelines):
  542. line2 = re.sub(r"(\s*COND_HEADER\s*=)",
  543. r"\1'#undef %s\\n'+" % cond,
  544. line)
  545. if line2 != line:
  546. found = True
  547. sourcelines[i] = line2
  548. assert found
  549. d = {}
  550. sourcelines.append('')
  551. exec '\n'.join(sourcelines) in d
  552. def test_no_AF_PACKET():
  553. _test_cond_include('AF_PACKET')
  554. def test_no_AF_NETLINK():
  555. _test_cond_include('AF_NETLINK')
  556. def test_thread_safe_gethostbyaddr():
  557. py.test.skip("hits non-thread-safe issues with ll2ctypes")
  558. import threading
  559. nthreads = 10
  560. ip = '8.8.8.8'
  561. domain = gethostbyaddr(ip)[0]
  562. result = [0] * nthreads
  563. threads = [None] * nthreads
  564. lock = threading.Lock()
  565. def lookup_addr(ip, i):
  566. name, aliases, address_list = gethostbyaddr(ip, lock)
  567. if name == domain:
  568. result[i] += 1
  569. for i in range(nthreads):
  570. threads[i] = threading.Thread(target = lookup_addr, args=[ip, i])
  571. threads[i].start()
  572. for i in range(nthreads):
  573. threads[i].join()
  574. assert sum(result) == nthreads
  575. def test_thread_safe_gethostbyname_ex():
  576. py.test.skip("hits non-thread-safe issues with ll2ctypes")
  577. import threading
  578. nthreads = 10
  579. domain = 'google.com'
  580. result = [0] * nthreads
  581. threads = [None] * nthreads
  582. lock = threading.Lock()
  583. def lookup_name(i):
  584. name, aliases, address_list = gethostbyname_ex(domain, lock)
  585. if name == domain:
  586. result[i] += 1
  587. for i in range(nthreads):
  588. threads[i] = threading.Thread(target = lookup_name, args=[i])
  589. threads[i].start()
  590. for i in range(nthreads):
  591. threads[i].join()
  592. assert sum(result) == nthreads
  593. def test_getaddrinfo_pydotorg_threadsafe():
  594. py.test.skip("hits non-thread-safe issues with ll2ctypes")
  595. import threading
  596. nthreads = 10
  597. result = [0] * nthreads
  598. threads = [None] * nthreads
  599. for i in range(nthreads):
  600. threads[i] = threading.Thread(target = getaddrinfo_pydotorg, args=[i, result])
  601. threads[i].start()
  602. for i in range(nthreads):
  603. threads[i].join()
  604. assert sum(result) == nthreads
  605. def test_translate_netdb_lock():
  606. def f():
  607. rsocket_startup()
  608. gethostbyaddr("localhost")
  609. return 0
  610. fc = compile(f, [])
  611. assert fc() == 0
  612. def test_translate_netdb_lock_thread():
  613. def f():
  614. rsocket_startup()
  615. gethostbyaddr("localhost")
  616. return 0
  617. fc = compile(f, [], thread=True)
  618. assert fc() == 0
  619. def test_socket_saves_errno(tmpdir):
  620. # ensure errno is set to a known value...
  621. unconnected_sock = RSocket()
  622. e = py.test.raises(CSocketError, unconnected_sock.recv, 1024)
  623. # ...which is ENOTCONN
  624. assert e.value.errno == errno.ENOTCONN
  625. e = py.test.raises(CSocketError,
  626. RSocket,
  627. family=AF_INET, type=SOCK_STREAM, proto=SOL_UDP)
  628. assert e.value.errno in (errno.EPROTOTYPE, errno.EPROTONOSUPPORT)