PageRenderTime 67ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/pypy/module/_socket/test/test_sock_app.py

https://bitbucket.org/uiappstore/pypy
Python | 674 lines | 640 code | 22 blank | 12 comment | 11 complexity | 1a804d61a50ceb763debfab50056c686 MD5 | raw file
  1. from pypy.conftest import gettestobjspace
  2. import sys
  3. import py
  4. from pypy.tool.udir import udir
  5. from pypy.rlib import rsocket
  6. from pypy.rpython.lltypesystem import lltype, rffi
  7. def setup_module(mod):
  8. mod.space = gettestobjspace(usemodules=['_socket', 'array'])
  9. global socket
  10. import socket
  11. mod.w_socket = space.appexec([], "(): import _socket as m; return m")
  12. mod.path = udir.join('fd')
  13. mod.path.write('fo')
  14. mod.raises = py.test.raises # make raises available from app-level tests
  15. mod.skip = py.test.skip
  16. def test_gethostname():
  17. host = space.appexec([w_socket], "(_socket): return _socket.gethostname()")
  18. assert space.unwrap(host) == socket.gethostname()
  19. def test_gethostbyname():
  20. host = "localhost"
  21. ip = space.appexec([w_socket, space.wrap(host)],
  22. "(_socket, host): return _socket.gethostbyname(host)")
  23. assert space.unwrap(ip) == socket.gethostbyname(host)
  24. def test_gethostbyname_ex():
  25. host = "localhost"
  26. ip = space.appexec([w_socket, space.wrap(host)],
  27. "(_socket, host): return _socket.gethostbyname_ex(host)")
  28. assert isinstance(space.unwrap(ip), tuple)
  29. assert space.unwrap(ip) == socket.gethostbyname_ex(host)
  30. def test_gethostbyaddr():
  31. host = "localhost"
  32. expected = socket.gethostbyaddr(host)
  33. expecteds = (expected, expected[:2]+(['0.0.0.0'],))
  34. ip = space.appexec([w_socket, space.wrap(host)],
  35. "(_socket, host): return _socket.gethostbyaddr(host)")
  36. assert space.unwrap(ip) in expecteds
  37. host = "127.0.0.1"
  38. expected = socket.gethostbyaddr(host)
  39. expecteds = (expected, expected[:2]+(['0.0.0.0'],))
  40. ip = space.appexec([w_socket, space.wrap(host)],
  41. "(_socket, host): return _socket.gethostbyaddr(host)")
  42. assert space.unwrap(ip) in expecteds
  43. def test_getservbyname():
  44. name = "smtp"
  45. # 2 args version
  46. port = space.appexec([w_socket, space.wrap(name)],
  47. "(_socket, name): return _socket.getservbyname(name, 'tcp')")
  48. assert space.unwrap(port) == 25
  49. # 1 arg version
  50. if sys.version_info < (2, 4):
  51. py.test.skip("getservbyname second argument is not optional before python 2.4")
  52. port = space.appexec([w_socket, space.wrap(name)],
  53. "(_socket, name): return _socket.getservbyname(name)")
  54. assert space.unwrap(port) == 25
  55. def test_getservbyport():
  56. if sys.version_info < (2, 4):
  57. py.test.skip("getservbyport does not exist before python 2.4")
  58. port = 25
  59. # 2 args version
  60. name = space.appexec([w_socket, space.wrap(port)],
  61. "(_socket, port): return _socket.getservbyport(port, 'tcp')")
  62. assert space.unwrap(name) == "smtp"
  63. name = space.appexec([w_socket, space.wrap(port)],
  64. """(_socket, port):
  65. try:
  66. return _socket.getservbyport(port, 42)
  67. except TypeError:
  68. return 'OK'
  69. """)
  70. assert space.unwrap(name) == 'OK'
  71. # 1 arg version
  72. name = space.appexec([w_socket, space.wrap(port)],
  73. "(_socket, port): return _socket.getservbyport(port)")
  74. assert space.unwrap(name) == "smtp"
  75. from pypy.interpreter.error import OperationError
  76. exc = raises(OperationError, space.appexec,
  77. [w_socket], "(_socket): return _socket.getservbyport(-1)")
  78. assert exc.value.match(space, space.w_ValueError)
  79. def test_getprotobyname():
  80. name = "tcp"
  81. w_n = space.appexec([w_socket, space.wrap(name)],
  82. "(_socket, name): return _socket.getprotobyname(name)")
  83. assert space.unwrap(w_n) == socket.IPPROTO_TCP
  84. def test_fromfd():
  85. # XXX review
  86. if not hasattr(socket, 'fromfd'):
  87. py.test.skip("No socket.fromfd on this platform")
  88. orig_fd = path.open()
  89. fd = space.appexec([w_socket, space.wrap(orig_fd.fileno()),
  90. space.wrap(socket.AF_INET), space.wrap(socket.SOCK_STREAM),
  91. space.wrap(0)],
  92. """(_socket, fd, family, type, proto):
  93. return _socket.fromfd(fd, family, type, proto)""")
  94. assert space.unwrap(space.call_method(fd, 'fileno'))
  95. fd = space.appexec([w_socket, space.wrap(orig_fd.fileno()),
  96. space.wrap(socket.AF_INET), space.wrap(socket.SOCK_STREAM)],
  97. """(_socket, fd, family, type):
  98. return _socket.fromfd(fd, family, type)""")
  99. assert space.unwrap(space.call_method(fd, 'fileno'))
  100. def test_ntohs():
  101. w_n = space.appexec([w_socket, space.wrap(125)],
  102. "(_socket, x): return _socket.ntohs(x)")
  103. assert space.unwrap(w_n) == socket.ntohs(125)
  104. def test_ntohl():
  105. w_n = space.appexec([w_socket, space.wrap(125)],
  106. "(_socket, x): return _socket.ntohl(x)")
  107. assert space.unwrap(w_n) == socket.ntohl(125)
  108. w_n = space.appexec([w_socket, space.wrap(0x89abcdef)],
  109. "(_socket, x): return _socket.ntohl(x)")
  110. assert space.unwrap(w_n) in (0x89abcdef, 0xefcdab89)
  111. space.raises_w(space.w_OverflowError, space.appexec,
  112. [w_socket, space.wrap(1<<32)],
  113. "(_socket, x): return _socket.ntohl(x)")
  114. def test_htons():
  115. w_n = space.appexec([w_socket, space.wrap(125)],
  116. "(_socket, x): return _socket.htons(x)")
  117. assert space.unwrap(w_n) == socket.htons(125)
  118. def test_htonl():
  119. w_n = space.appexec([w_socket, space.wrap(125)],
  120. "(_socket, x): return _socket.htonl(x)")
  121. assert space.unwrap(w_n) == socket.htonl(125)
  122. w_n = space.appexec([w_socket, space.wrap(0x89abcdef)],
  123. "(_socket, x): return _socket.htonl(x)")
  124. assert space.unwrap(w_n) in (0x89abcdef, 0xefcdab89)
  125. space.raises_w(space.w_OverflowError, space.appexec,
  126. [w_socket, space.wrap(1<<32)],
  127. "(_socket, x): return _socket.htonl(x)")
  128. def test_aton_ntoa():
  129. ip = '123.45.67.89'
  130. packed = socket.inet_aton(ip)
  131. w_p = space.appexec([w_socket, space.wrap(ip)],
  132. "(_socket, ip): return _socket.inet_aton(ip)")
  133. assert space.unwrap(w_p) == packed
  134. w_ip = space.appexec([w_socket, space.wrap(packed)],
  135. "(_socket, p): return _socket.inet_ntoa(p)")
  136. assert space.unwrap(w_ip) == ip
  137. def test_pton_ntop_ipv4():
  138. if not hasattr(socket, 'inet_pton'):
  139. py.test.skip('No socket.inet_pton on this platform')
  140. tests = [
  141. ("123.45.67.89", "\x7b\x2d\x43\x59"),
  142. ("0.0.0.0", "\x00" * 4),
  143. ("255.255.255.255", "\xff" * 4),
  144. ]
  145. for ip, packed in tests:
  146. w_p = space.appexec([w_socket, space.wrap(ip)],
  147. "(_socket, ip): return _socket.inet_pton(_socket.AF_INET, ip)")
  148. assert space.unwrap(w_p) == packed
  149. w_ip = space.appexec([w_socket, w_p],
  150. "(_socket, p): return _socket.inet_ntop(_socket.AF_INET, p)")
  151. assert space.unwrap(w_ip) == ip
  152. def test_ntop_ipv6():
  153. if not hasattr(socket, 'inet_pton'):
  154. py.test.skip('No socket.inet_pton on this platform')
  155. if not socket.has_ipv6:
  156. py.test.skip("No IPv6 on this platform")
  157. tests = [
  158. ("\x00" * 16, "::"),
  159. ("\x01" * 16, ":".join(["101"] * 8)),
  160. ("\x00\x00\x10\x10" * 4, None), #"::1010:" + ":".join(["0:1010"] * 3)),
  161. ("\x00" * 12 + "\x01\x02\x03\x04", "::1.2.3.4"),
  162. ("\x00" * 10 + "\xff\xff\x01\x02\x03\x04", "::ffff:1.2.3.4"),
  163. ]
  164. for packed, ip in tests:
  165. w_ip = space.appexec([w_socket, space.wrap(packed)],
  166. "(_socket, packed): return _socket.inet_ntop(_socket.AF_INET6, packed)")
  167. if ip is not None: # else don't check for the precise representation
  168. assert space.unwrap(w_ip) == ip
  169. w_packed = space.appexec([w_socket, w_ip],
  170. "(_socket, ip): return _socket.inet_pton(_socket.AF_INET6, ip)")
  171. assert space.unwrap(w_packed) == packed
  172. def test_pton_ipv6():
  173. if not hasattr(socket, 'inet_pton'):
  174. py.test.skip('No socket.inet_pton on this platform')
  175. if not socket.has_ipv6:
  176. py.test.skip("No IPv6 on this platform")
  177. tests = [
  178. ("\x00" * 16, "::"),
  179. ("\x01" * 16, ":".join(["101"] * 8)),
  180. ("\x00\x01" + "\x00" * 12 + "\x00\x02", "1::2"),
  181. ("\x00" * 4 + "\x00\x01" * 6, "::1:1:1:1:1:1"),
  182. ("\x00\x01" * 6 + "\x00" * 4, "1:1:1:1:1:1::"),
  183. ("\xab\xcd\xef\00" + "\x00" * 12, "ABCD:EF00::"),
  184. ("\xab\xcd\xef\00" + "\x00" * 12, "abcd:ef00::"),
  185. ("\x00\x00\x10\x10" * 4, "::1010:" + ":".join(["0:1010"] * 3)),
  186. ("\x00" * 12 + "\x01\x02\x03\x04", "::1.2.3.4"),
  187. ("\x00" * 10 + "\xff\xff\x01\x02\x03\x04", "::ffff:1.2.3.4"),
  188. ]
  189. for packed, ip in tests:
  190. w_packed = space.appexec([w_socket, space.wrap(ip)],
  191. "(_socket, ip): return _socket.inet_pton(_socket.AF_INET6, ip)")
  192. assert space.unwrap(w_packed) == packed
  193. def test_has_ipv6():
  194. py.test.skip("has_ipv6 is always True on PyPy for now")
  195. res = space.appexec([w_socket], "(_socket): return _socket.has_ipv6")
  196. assert space.unwrap(res) == socket.has_ipv6
  197. def test_getaddrinfo():
  198. host = "localhost"
  199. port = 25
  200. info = socket.getaddrinfo(host, port)
  201. w_l = space.appexec([w_socket, space.wrap(host), space.wrap(port)],
  202. "(_socket, host, port): return _socket.getaddrinfo(host, port)")
  203. assert space.unwrap(w_l) == info
  204. py.test.skip("Unicode conversion is too slow")
  205. w_l = space.appexec([w_socket, space.wrap(unicode(host)), space.wrap(port)],
  206. "(_socket, host, port): return _socket.getaddrinfo(host, port)")
  207. assert space.unwrap(w_l) == info
  208. def test_unknown_addr_as_object():
  209. c_addr = lltype.malloc(rsocket._c.sockaddr, flavor='raw')
  210. c_addr.c_sa_data[0] = 'c'
  211. rffi.setintfield(c_addr, 'c_sa_family', 15)
  212. # XXX what size to pass here? for the purpose of this test it has
  213. # to be short enough so we have some data, 1 sounds good enough
  214. # + sizeof USHORT
  215. w_obj = rsocket.Address(c_addr, 1 + 2).as_object(-1, space)
  216. assert space.is_true(space.isinstance(w_obj, space.w_tuple))
  217. assert space.int_w(space.getitem(w_obj, space.wrap(0))) == 15
  218. assert space.str_w(space.getitem(w_obj, space.wrap(1))) == 'c'
  219. def test_addr_raw_packet():
  220. if not hasattr(rsocket._c, 'sockaddr_ll'):
  221. py.test.skip("posix specific test")
  222. c_addr_ll = lltype.malloc(rsocket._c.sockaddr_ll, flavor='raw')
  223. addrlen = rffi.sizeof(rsocket._c.sockaddr_ll)
  224. c_addr = rffi.cast(lltype.Ptr(rsocket._c.sockaddr), c_addr_ll)
  225. rffi.setintfield(c_addr_ll, 'c_sll_ifindex', 1)
  226. rffi.setintfield(c_addr_ll, 'c_sll_protocol', 8)
  227. rffi.setintfield(c_addr_ll, 'c_sll_pkttype', 13)
  228. rffi.setintfield(c_addr_ll, 'c_sll_hatype', 0)
  229. rffi.setintfield(c_addr_ll, 'c_sll_halen', 3)
  230. c_addr_ll.c_sll_addr[0] = 'a'
  231. c_addr_ll.c_sll_addr[1] = 'b'
  232. c_addr_ll.c_sll_addr[2] = 'c'
  233. rffi.setintfield(c_addr, 'c_sa_family', socket.AF_PACKET)
  234. # fd needs to be somehow valid
  235. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  236. fd = s.fileno()
  237. w_obj = rsocket.make_address(c_addr, addrlen).as_object(fd, space)
  238. lltype.free(c_addr_ll, flavor='raw')
  239. assert space.is_true(space.eq(w_obj, space.newtuple([
  240. space.wrap('lo'),
  241. space.wrap(socket.ntohs(8)),
  242. space.wrap(13),
  243. space.wrap(False),
  244. space.wrap("abc"),
  245. ])))
  246. def test_getnameinfo():
  247. host = "127.0.0.1"
  248. port = 25
  249. info = socket.getnameinfo((host, port), 0)
  250. w_l = space.appexec([w_socket, space.wrap(host), space.wrap(port)],
  251. "(_socket, host, port): return _socket.getnameinfo((host, port), 0)")
  252. assert space.unwrap(w_l) == info
  253. def test_timeout():
  254. space.appexec([w_socket, space.wrap(25.4)],
  255. "(_socket, timeout): _socket.setdefaulttimeout(timeout)")
  256. w_t = space.appexec([w_socket],
  257. "(_socket): return _socket.getdefaulttimeout()")
  258. assert space.unwrap(w_t) == 25.4
  259. space.appexec([w_socket, space.w_None],
  260. "(_socket, timeout): _socket.setdefaulttimeout(timeout)")
  261. w_t = space.appexec([w_socket],
  262. "(_socket): return _socket.getdefaulttimeout()")
  263. assert space.unwrap(w_t) is None
  264. # XXX also need tests for other connection and timeout errors
  265. class AppTestSocket:
  266. def setup_class(cls):
  267. cls.space = space
  268. cls.w_udir = space.wrap(str(udir))
  269. def test_ntoa_exception(self):
  270. import _socket
  271. raises(_socket.error, _socket.inet_ntoa, "ab")
  272. def test_aton_exceptions(self):
  273. import _socket
  274. tests = ["127.0.0.256", "127.0.0.255555555555555555", "127.2b.0.0",
  275. "127.2.0.0.1", "127.2.0."]
  276. for ip in tests:
  277. raises(_socket.error, _socket.inet_aton, ip)
  278. def test_ntop_exceptions(self):
  279. import _socket
  280. if not hasattr(_socket, 'inet_ntop'):
  281. skip('No socket.inet_pton on this platform')
  282. for family, packed, exception in \
  283. [(_socket.AF_INET + _socket.AF_INET6, "", _socket.error),
  284. (_socket.AF_INET, "a", ValueError),
  285. (_socket.AF_INET6, "a", ValueError),
  286. (_socket.AF_INET, u"aa\u2222a", UnicodeEncodeError)]:
  287. raises(exception, _socket.inet_ntop, family, packed)
  288. def test_pton_exceptions(self):
  289. import _socket
  290. if not hasattr(_socket, 'inet_pton'):
  291. skip('No socket.inet_pton on this platform')
  292. tests = [
  293. (_socket.AF_INET + _socket.AF_INET6, ""),
  294. (_socket.AF_INET, "127.0.0.256"),
  295. (_socket.AF_INET, "127.0.0.255555555555555555"),
  296. (_socket.AF_INET, "127.2b.0.0"),
  297. (_socket.AF_INET, "127.2.0.0.1"),
  298. (_socket.AF_INET, "127.2..0"),
  299. (_socket.AF_INET6, "127.0.0.1"),
  300. (_socket.AF_INET6, "1::2::3"),
  301. (_socket.AF_INET6, "1:1:1:1:1:1:1:1:1"),
  302. (_socket.AF_INET6, "1:1:1:1:1:1:1:1::"),
  303. (_socket.AF_INET6, "1:1:1::1:1:1:1:1"),
  304. (_socket.AF_INET6, "1::22222:1"),
  305. (_socket.AF_INET6, "1::eg"),
  306. ]
  307. for family, ip in tests:
  308. raises(_socket.error, _socket.inet_pton, family, ip)
  309. def test_newsocket_error(self):
  310. import _socket
  311. raises(_socket.error, _socket.socket, 10001, _socket.SOCK_STREAM, 0)
  312. def test_socket_fileno(self):
  313. import _socket
  314. s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
  315. assert s.fileno() > -1
  316. assert isinstance(s.fileno(), int)
  317. def test_socket_close(self):
  318. import _socket
  319. s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
  320. fileno = s.fileno()
  321. assert s.fileno() >= 0
  322. s.close()
  323. assert s.fileno() < 0
  324. s.close()
  325. def test_socket_close_error(self):
  326. import _socket, os
  327. if os.name == 'nt':
  328. skip("Windows sockets are not files")
  329. s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
  330. os.close(s.fileno())
  331. raises(_socket.error, s.close)
  332. def test_socket_connect(self):
  333. import _socket, os
  334. s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
  335. # XXX temporarily we use python.org to test, will have more robust tests
  336. # in the absence of a network connection later when more parts of the
  337. # socket API are implemented. Currently skip the test if there is no
  338. # connection.
  339. try:
  340. s.connect(("www.python.org", 80))
  341. except _socket.gaierror, ex:
  342. skip("GAIError - probably no connection: %s" % str(ex.args))
  343. name = s.getpeername() # Will raise socket.error if not connected
  344. assert name[1] == 80
  345. s.close()
  346. def test_socket_connect_ex(self):
  347. import _socket
  348. s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
  349. # Make sure we get an app-level error, not an interp one.
  350. raises(_socket.gaierror, s.connect_ex, ("wrong.invalid", 80))
  351. s.close()
  352. def test_socket_connect_typeerrors(self):
  353. tests = [
  354. "",
  355. ("80"),
  356. ("80", "80"),
  357. (80, 80),
  358. ]
  359. import _socket
  360. s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
  361. for args in tests:
  362. raises((TypeError, ValueError), s.connect, args)
  363. s.close()
  364. def test_bigport(self):
  365. import _socket
  366. s = _socket.socket()
  367. raises(ValueError, s.connect, ("localhost", 1000000))
  368. raises(ValueError, s.connect, ("localhost", -1))
  369. def test_NtoH(self):
  370. import sys
  371. import _socket as socket
  372. # This just checks that htons etc. are their own inverse,
  373. # when looking at the lower 16 or 32 bits.
  374. sizes = {socket.htonl: 32, socket.ntohl: 32,
  375. socket.htons: 16, socket.ntohs: 16}
  376. for func, size in sizes.items():
  377. mask = (1L<<size) - 1
  378. for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210):
  379. assert i & mask == func(func(i&mask)) & mask
  380. swapped = func(mask)
  381. assert swapped & mask == mask
  382. try:
  383. func(-1)
  384. except (OverflowError, ValueError):
  385. pass
  386. else:
  387. assert False
  388. try:
  389. func(sys.maxint*2+2)
  390. except OverflowError:
  391. pass
  392. else:
  393. assert False
  394. def test_NtoH_overflow(self):
  395. skip("we are not checking for overflowing values yet")
  396. import _socket as socket
  397. # Checks that we cannot give too large values to htons etc.
  398. # Skipped for now; CPython 2.6 is also not consistent.
  399. sizes = {socket.htonl: 32, socket.ntohl: 32,
  400. socket.htons: 16, socket.ntohs: 16}
  401. for func, size in sizes.items():
  402. try:
  403. func(1L << size)
  404. except OverflowError:
  405. pass
  406. else:
  407. assert False
  408. def test_newsocket(self):
  409. import socket
  410. s = socket.socket()
  411. def test_getsetsockopt(self):
  412. import _socket as socket
  413. import struct
  414. # A socket sould start with reuse == 0
  415. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  416. reuse = s.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
  417. assert reuse == 0
  418. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  419. reuse = s.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
  420. assert reuse != 0
  421. # String case
  422. intsize = struct.calcsize('i')
  423. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  424. reusestr = s.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,
  425. intsize)
  426. (reuse,) = struct.unpack('i', reusestr)
  427. assert reuse == 0
  428. reusestr = struct.pack('i', 1)
  429. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, reusestr)
  430. reusestr = s.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,
  431. intsize)
  432. (reuse,) = struct.unpack('i', reusestr)
  433. assert reuse != 0
  434. def test_socket_ioctl(self):
  435. import _socket, sys
  436. if sys.platform != 'win32':
  437. skip("win32 only")
  438. assert hasattr(_socket.socket, 'ioctl')
  439. assert hasattr(_socket, 'SIO_RCVALL')
  440. assert hasattr(_socket, 'RCVALL_ON')
  441. assert hasattr(_socket, 'RCVALL_OFF')
  442. assert hasattr(_socket, 'SIO_KEEPALIVE_VALS')
  443. s = _socket.socket()
  444. raises(ValueError, s.ioctl, -1, None)
  445. s.ioctl(_socket.SIO_KEEPALIVE_VALS, (1, 100, 100))
  446. def test_dup(self):
  447. import _socket as socket
  448. if not hasattr(socket.socket, 'dup'):
  449. skip('No dup() on this platform')
  450. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  451. s.bind(('localhost', 0))
  452. s2 = s.dup()
  453. assert s.fileno() != s2.fileno()
  454. assert s.getsockname() == s2.getsockname()
  455. def test_buffer_or_unicode(self):
  456. # Test that send/sendall/sendto accept a buffer or a unicode as arg
  457. import _socket, os
  458. s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
  459. # XXX temporarily we use python.org to test, will have more robust tests
  460. # in the absence of a network connection later when more parts of the
  461. # socket API are implemented. Currently skip the test if there is no
  462. # connection.
  463. try:
  464. s.connect(("www.python.org", 80))
  465. except _socket.gaierror, ex:
  466. skip("GAIError - probably no connection: %s" % str(ex.args))
  467. s.send(buffer(''))
  468. s.sendall(buffer(''))
  469. s.send(u'')
  470. s.sendall(u'')
  471. raises(UnicodeEncodeError, s.send, u'\xe9')
  472. s.close()
  473. s = _socket.socket(_socket.AF_INET, _socket.SOCK_DGRAM, 0)
  474. s.sendto(buffer(''), ('localhost', 9)) # Send to discard port.
  475. s.close()
  476. def test_unix_socket_connect(self):
  477. import _socket, os
  478. if not hasattr(_socket, 'AF_UNIX'):
  479. skip('AF_UNIX not supported.')
  480. oldcwd = os.getcwd()
  481. os.chdir(self.udir)
  482. try:
  483. sockpath = 'app_test_unix_socket_connect'
  484. serversock = _socket.socket(_socket.AF_UNIX)
  485. serversock.bind(sockpath)
  486. serversock.listen(1)
  487. clientsock = _socket.socket(_socket.AF_UNIX)
  488. clientsock.connect(sockpath)
  489. s, addr = serversock.accept()
  490. assert not addr
  491. s.send('X')
  492. data = clientsock.recv(100)
  493. assert data == 'X'
  494. clientsock.send('Y')
  495. data = s.recv(100)
  496. assert data == 'Y'
  497. clientsock.close()
  498. s.close()
  499. finally:
  500. os.chdir(oldcwd)
  501. class AppTestSocketTCP:
  502. def setup_class(cls):
  503. cls.space = space
  504. HOST = 'localhost'
  505. def setup_method(self, method):
  506. w_HOST = space.wrap(self.HOST)
  507. self.w_serv = space.appexec([w_socket, w_HOST],
  508. '''(_socket, HOST):
  509. serv = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
  510. serv.bind((HOST, 0))
  511. serv.listen(1)
  512. return serv
  513. ''')
  514. def teardown_method(self, method):
  515. if hasattr(self, 'w_serv'):
  516. space.appexec([self.w_serv], '(serv): serv.close()')
  517. self.w_serv = None
  518. def test_timeout(self):
  519. from _socket import timeout
  520. def raise_timeout():
  521. self.serv.settimeout(1.0)
  522. self.serv.accept()
  523. raises(timeout, raise_timeout)
  524. def test_timeout_zero(self):
  525. from _socket import error
  526. def raise_error():
  527. self.serv.settimeout(0.0)
  528. foo = self.serv.accept()
  529. raises(error, raise_error)
  530. def test_recv_send_timeout(self):
  531. from _socket import socket, timeout
  532. cli = socket()
  533. cli.connect(self.serv.getsockname())
  534. t, addr = self.serv.accept()
  535. cli.settimeout(1.0)
  536. # test recv() timeout
  537. t.send('*')
  538. buf = cli.recv(100)
  539. assert buf == '*'
  540. raises(timeout, cli.recv, 100)
  541. # test that send() works
  542. count = cli.send('!')
  543. assert count == 1
  544. buf = t.recv(1)
  545. assert buf == '!'
  546. # test that sendall() works
  547. cli.sendall('?')
  548. assert count == 1
  549. buf = t.recv(1)
  550. assert buf == '?'
  551. # test send() timeout
  552. try:
  553. while 1:
  554. cli.send('foobar' * 70)
  555. except timeout:
  556. pass
  557. # test sendall() timeout
  558. raises(timeout, cli.sendall, 'foobar' * 70)
  559. # done
  560. cli.close()
  561. t.close()
  562. def test_recv_into(self):
  563. import socket
  564. import array
  565. MSG = 'dupa was here\n'
  566. cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  567. cli.connect(self.serv.getsockname())
  568. conn, addr = self.serv.accept()
  569. buf = buffer(MSG)
  570. conn.send(buf)
  571. buf = array.array('c', ' '*1024)
  572. nbytes = cli.recv_into(buf)
  573. assert nbytes == len(MSG)
  574. msg = buf.tostring()[:len(MSG)]
  575. assert msg == MSG
  576. def test_recvfrom_into(self):
  577. import socket
  578. import array
  579. MSG = 'dupa was here\n'
  580. cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  581. cli.connect(self.serv.getsockname())
  582. conn, addr = self.serv.accept()
  583. buf = buffer(MSG)
  584. conn.send(buf)
  585. buf = array.array('c', ' '*1024)
  586. nbytes, addr = cli.recvfrom_into(buf)
  587. assert nbytes == len(MSG)
  588. msg = buf.tostring()[:len(MSG)]
  589. assert msg == MSG
  590. def test_family(self):
  591. import socket
  592. cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  593. assert cli.family == socket.AF_INET
  594. class AppTestErrno:
  595. def setup_class(cls):
  596. cls.space = space
  597. def test_errno(self):
  598. from socket import socket, AF_INET, SOCK_STREAM, error
  599. import errno
  600. s = socket(AF_INET, SOCK_STREAM)
  601. exc = raises(error, s.accept)
  602. assert isinstance(exc.value, error)
  603. assert isinstance(exc.value, IOError)
  604. # error is EINVAL, or WSAEINVAL on Windows
  605. assert exc.value.errno == getattr(errno, 'WSAEINVAL', errno.EINVAL)
  606. assert isinstance(exc.value.message, str)