PageRenderTime 47ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://bitbucket.org/jphalip/pypy
Python | 690 lines | 652 code | 23 blank | 15 comment | 11 complexity | 7733db4d42da88d8ac8fbfaca6f4ba4e MD5 | raw file
  1. import sys
  2. import py
  3. from pypy.tool.pytest.objspace import gettestobjspace
  4. from rpython.tool.udir import udir
  5. from rpython.rlib import rsocket
  6. from rpython.rtyper.lltypesystem import lltype, rffi
  7. def setup_module(mod):
  8. mod.space = gettestobjspace(usemodules=['_socket', 'array', 'struct'])
  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. from pypy.module._socket.interp_socket import addr_as_object
  210. c_addr = lltype.malloc(rsocket._c.sockaddr, flavor='raw')
  211. c_addr.c_sa_data[0] = 'c'
  212. rffi.setintfield(c_addr, 'c_sa_family', 15)
  213. # XXX what size to pass here? for the purpose of this test it has
  214. # to be short enough so we have some data, 1 sounds good enough
  215. # + sizeof USHORT
  216. w_obj = addr_as_object(rsocket.Address(c_addr, 1 + 2), -1, space)
  217. assert space.is_true(space.isinstance(w_obj, space.w_tuple))
  218. assert space.int_w(space.getitem(w_obj, space.wrap(0))) == 15
  219. assert space.str_w(space.getitem(w_obj, space.wrap(1))) == 'c'
  220. def test_addr_raw_packet():
  221. from pypy.module._socket.interp_socket import addr_as_object
  222. if not hasattr(rsocket._c, 'sockaddr_ll'):
  223. py.test.skip("posix specific test")
  224. # HACK: To get the correct interface numer of lo, which in most cases is 1,
  225. # but can be anything (i.e. 39), we need to call the libc function
  226. # if_nametoindex to get the correct index
  227. import ctypes
  228. libc = ctypes.CDLL(ctypes.util.find_library('c'))
  229. ifnum = libc.if_nametoindex('lo')
  230. c_addr_ll = lltype.malloc(rsocket._c.sockaddr_ll, flavor='raw')
  231. addrlen = rffi.sizeof(rsocket._c.sockaddr_ll)
  232. c_addr = rffi.cast(lltype.Ptr(rsocket._c.sockaddr), c_addr_ll)
  233. rffi.setintfield(c_addr_ll, 'c_sll_ifindex', ifnum)
  234. rffi.setintfield(c_addr_ll, 'c_sll_protocol', 8)
  235. rffi.setintfield(c_addr_ll, 'c_sll_pkttype', 13)
  236. rffi.setintfield(c_addr_ll, 'c_sll_hatype', 0)
  237. rffi.setintfield(c_addr_ll, 'c_sll_halen', 3)
  238. c_addr_ll.c_sll_addr[0] = 'a'
  239. c_addr_ll.c_sll_addr[1] = 'b'
  240. c_addr_ll.c_sll_addr[2] = 'c'
  241. rffi.setintfield(c_addr, 'c_sa_family', socket.AF_PACKET)
  242. # fd needs to be somehow valid
  243. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  244. fd = s.fileno()
  245. w_obj = addr_as_object(rsocket.make_address(c_addr, addrlen), fd, space)
  246. lltype.free(c_addr_ll, flavor='raw')
  247. assert space.is_true(space.eq(w_obj, space.newtuple([
  248. space.wrap('lo'),
  249. space.wrap(socket.ntohs(8)),
  250. space.wrap(13),
  251. space.wrap(False),
  252. space.wrap("abc"),
  253. ])))
  254. def test_getnameinfo():
  255. host = "127.0.0.1"
  256. port = 25
  257. info = socket.getnameinfo((host, port), 0)
  258. w_l = space.appexec([w_socket, space.wrap(host), space.wrap(port)],
  259. "(_socket, host, port): return _socket.getnameinfo((host, port), 0)")
  260. assert space.unwrap(w_l) == info
  261. def test_timeout():
  262. space.appexec([w_socket, space.wrap(25.4)],
  263. "(_socket, timeout): _socket.setdefaulttimeout(timeout)")
  264. w_t = space.appexec([w_socket],
  265. "(_socket): return _socket.getdefaulttimeout()")
  266. assert space.unwrap(w_t) == 25.4
  267. space.appexec([w_socket, space.w_None],
  268. "(_socket, timeout): _socket.setdefaulttimeout(timeout)")
  269. w_t = space.appexec([w_socket],
  270. "(_socket): return _socket.getdefaulttimeout()")
  271. assert space.unwrap(w_t) is None
  272. # XXX also need tests for other connection and timeout errors
  273. class AppTestSocket:
  274. def setup_class(cls):
  275. cls.space = space
  276. cls.w_udir = space.wrap(str(udir))
  277. def test_ntoa_exception(self):
  278. import _socket
  279. raises(_socket.error, _socket.inet_ntoa, "ab")
  280. def test_aton_exceptions(self):
  281. import _socket
  282. tests = ["127.0.0.256", "127.0.0.255555555555555555", "127.2b.0.0",
  283. "127.2.0.0.1", "127.2.0."]
  284. for ip in tests:
  285. raises(_socket.error, _socket.inet_aton, ip)
  286. def test_ntop_exceptions(self):
  287. import _socket
  288. if not hasattr(_socket, 'inet_ntop'):
  289. skip('No socket.inet_pton on this platform')
  290. for family, packed, exception in \
  291. [(_socket.AF_INET + _socket.AF_INET6, "", _socket.error),
  292. (_socket.AF_INET, "a", ValueError),
  293. (_socket.AF_INET6, "a", ValueError),
  294. (_socket.AF_INET, u"aa\u2222a", UnicodeEncodeError)]:
  295. raises(exception, _socket.inet_ntop, family, packed)
  296. def test_pton_exceptions(self):
  297. import _socket
  298. if not hasattr(_socket, 'inet_pton'):
  299. skip('No socket.inet_pton on this platform')
  300. tests = [
  301. (_socket.AF_INET + _socket.AF_INET6, ""),
  302. (_socket.AF_INET, "127.0.0.256"),
  303. (_socket.AF_INET, "127.0.0.255555555555555555"),
  304. (_socket.AF_INET, "127.2b.0.0"),
  305. (_socket.AF_INET, "127.2.0.0.1"),
  306. (_socket.AF_INET, "127.2..0"),
  307. (_socket.AF_INET6, "127.0.0.1"),
  308. (_socket.AF_INET6, "1::2::3"),
  309. (_socket.AF_INET6, "1:1:1:1:1:1:1:1:1"),
  310. (_socket.AF_INET6, "1:1:1:1:1:1:1:1::"),
  311. (_socket.AF_INET6, "1:1:1::1:1:1:1:1"),
  312. (_socket.AF_INET6, "1::22222:1"),
  313. (_socket.AF_INET6, "1::eg"),
  314. ]
  315. for family, ip in tests:
  316. raises(_socket.error, _socket.inet_pton, family, ip)
  317. def test_newsocket_error(self):
  318. import _socket
  319. raises(_socket.error, _socket.socket, 10001, _socket.SOCK_STREAM, 0)
  320. def test_socket_fileno(self):
  321. import _socket
  322. s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
  323. assert s.fileno() > -1
  324. assert isinstance(s.fileno(), int)
  325. def test_socket_close(self):
  326. import _socket, os
  327. s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
  328. fileno = s.fileno()
  329. assert s.fileno() >= 0
  330. s.close()
  331. assert s.fileno() < 0
  332. s.close()
  333. if os.name != 'nt':
  334. raises(OSError, os.close, fileno)
  335. def test_socket_close_error(self):
  336. import _socket, os
  337. if os.name == 'nt':
  338. skip("Windows sockets are not files")
  339. s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
  340. os.close(s.fileno())
  341. s.close()
  342. def test_socket_connect(self):
  343. import _socket, os
  344. s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
  345. # it would be nice to have a test which works even if there is no
  346. # network connection. However, this one is "good enough" for now. Skip
  347. # it if there is no connection.
  348. try:
  349. s.connect(("www.python.org", 80))
  350. except _socket.gaierror, ex:
  351. skip("GAIError - probably no connection: %s" % str(ex.args))
  352. name = s.getpeername() # Will raise socket.error if not connected
  353. assert name[1] == 80
  354. s.close()
  355. def test_socket_connect_ex(self):
  356. import _socket
  357. s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
  358. # Make sure we get an app-level error, not an interp one.
  359. raises(_socket.gaierror, s.connect_ex, ("wrong.invalid", 80))
  360. s.close()
  361. def test_socket_connect_typeerrors(self):
  362. tests = [
  363. "",
  364. ("80"),
  365. ("80", "80"),
  366. (80, 80),
  367. ]
  368. import _socket
  369. s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
  370. for args in tests:
  371. raises((TypeError, ValueError), s.connect, args)
  372. s.close()
  373. def test_bigport(self):
  374. import _socket
  375. s = _socket.socket()
  376. raises(ValueError, s.connect, ("localhost", 1000000))
  377. raises(ValueError, s.connect, ("localhost", -1))
  378. def test_NtoH(self):
  379. import sys
  380. import _socket as socket
  381. # This just checks that htons etc. are their own inverse,
  382. # when looking at the lower 16 or 32 bits.
  383. sizes = {socket.htonl: 32, socket.ntohl: 32,
  384. socket.htons: 16, socket.ntohs: 16}
  385. for func, size in sizes.items():
  386. mask = (1L<<size) - 1
  387. for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210):
  388. assert i & mask == func(func(i&mask)) & mask
  389. swapped = func(mask)
  390. assert swapped & mask == mask
  391. try:
  392. func(-1)
  393. except (OverflowError, ValueError):
  394. pass
  395. else:
  396. assert False
  397. try:
  398. func(sys.maxint*2+2)
  399. except OverflowError:
  400. pass
  401. else:
  402. assert False
  403. def test_NtoH_overflow(self):
  404. skip("we are not checking for overflowing values yet")
  405. import _socket as socket
  406. # Checks that we cannot give too large values to htons etc.
  407. # Skipped for now; CPython 2.6 is also not consistent.
  408. sizes = {socket.htonl: 32, socket.ntohl: 32,
  409. socket.htons: 16, socket.ntohs: 16}
  410. for func, size in sizes.items():
  411. try:
  412. func(1L << size)
  413. except OverflowError:
  414. pass
  415. else:
  416. assert False
  417. def test_newsocket(self):
  418. import socket
  419. s = socket.socket()
  420. def test_getsetsockopt(self):
  421. import _socket as socket
  422. import struct
  423. # A socket sould start with reuse == 0
  424. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  425. reuse = s.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
  426. assert reuse == 0
  427. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  428. reuse = s.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
  429. assert reuse != 0
  430. # String case
  431. intsize = struct.calcsize('i')
  432. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  433. reusestr = s.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,
  434. intsize)
  435. (reuse,) = struct.unpack('i', reusestr)
  436. assert reuse == 0
  437. reusestr = struct.pack('i', 1)
  438. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, reusestr)
  439. reusestr = s.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,
  440. intsize)
  441. (reuse,) = struct.unpack('i', reusestr)
  442. assert reuse != 0
  443. def test_socket_ioctl(self):
  444. import _socket, sys
  445. if sys.platform != 'win32':
  446. skip("win32 only")
  447. assert hasattr(_socket.socket, 'ioctl')
  448. assert hasattr(_socket, 'SIO_RCVALL')
  449. assert hasattr(_socket, 'RCVALL_ON')
  450. assert hasattr(_socket, 'RCVALL_OFF')
  451. assert hasattr(_socket, 'SIO_KEEPALIVE_VALS')
  452. s = _socket.socket()
  453. raises(ValueError, s.ioctl, -1, None)
  454. s.ioctl(_socket.SIO_KEEPALIVE_VALS, (1, 100, 100))
  455. def test_dup(self):
  456. import _socket as socket
  457. if not hasattr(socket.socket, 'dup'):
  458. skip('No dup() on this platform')
  459. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  460. s.bind(('localhost', 0))
  461. s2 = s.dup()
  462. assert s.fileno() != s2.fileno()
  463. assert s.getsockname() == s2.getsockname()
  464. def test_buffer_or_unicode(self):
  465. # Test that send/sendall/sendto accept a buffer or a unicode as arg
  466. import _socket, os
  467. s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
  468. # XXX temporarily we use python.org to test, will have more robust tests
  469. # in the absence of a network connection later when more parts of the
  470. # socket API are implemented. Currently skip the test if there is no
  471. # connection.
  472. try:
  473. s.connect(("www.python.org", 80))
  474. except _socket.gaierror, ex:
  475. skip("GAIError - probably no connection: %s" % str(ex.args))
  476. s.send(buffer(''))
  477. s.sendall(buffer(''))
  478. s.send(u'')
  479. s.sendall(u'')
  480. raises(UnicodeEncodeError, s.send, u'\xe9')
  481. s.close()
  482. s = _socket.socket(_socket.AF_INET, _socket.SOCK_DGRAM, 0)
  483. s.sendto(buffer(''), ('localhost', 9)) # Send to discard port.
  484. s.close()
  485. def test_unix_socket_connect(self):
  486. import _socket, os
  487. if not hasattr(_socket, 'AF_UNIX'):
  488. skip('AF_UNIX not supported.')
  489. oldcwd = os.getcwd()
  490. os.chdir(self.udir)
  491. try:
  492. sockpath = 'app_test_unix_socket_connect'
  493. serversock = _socket.socket(_socket.AF_UNIX)
  494. serversock.bind(sockpath)
  495. serversock.listen(1)
  496. clientsock = _socket.socket(_socket.AF_UNIX)
  497. clientsock.connect(sockpath)
  498. s, addr = serversock.accept()
  499. assert not addr
  500. s.send('X')
  501. data = clientsock.recv(100)
  502. assert data == 'X'
  503. clientsock.send('Y')
  504. data = s.recv(100)
  505. assert data == 'Y'
  506. clientsock.close()
  507. s.close()
  508. finally:
  509. os.chdir(oldcwd)
  510. class AppTestSocketTCP:
  511. def setup_class(cls):
  512. cls.space = space
  513. HOST = 'localhost'
  514. def setup_method(self, method):
  515. w_HOST = space.wrap(self.HOST)
  516. self.w_serv = space.appexec([w_socket, w_HOST],
  517. '''(_socket, HOST):
  518. serv = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
  519. serv.bind((HOST, 0))
  520. serv.listen(1)
  521. return serv
  522. ''')
  523. def teardown_method(self, method):
  524. if hasattr(self, 'w_serv'):
  525. space.appexec([self.w_serv], '(serv): serv.close()')
  526. self.w_serv = None
  527. def test_timeout(self):
  528. from _socket import timeout
  529. def raise_timeout():
  530. self.serv.settimeout(1.0)
  531. self.serv.accept()
  532. raises(timeout, raise_timeout)
  533. def test_timeout_zero(self):
  534. from _socket import error
  535. def raise_error():
  536. self.serv.settimeout(0.0)
  537. foo = self.serv.accept()
  538. raises(error, raise_error)
  539. def test_recv_send_timeout(self):
  540. from _socket import socket, timeout
  541. cli = socket()
  542. cli.connect(self.serv.getsockname())
  543. t, addr = self.serv.accept()
  544. cli.settimeout(1.0)
  545. # test recv() timeout
  546. t.send('*')
  547. buf = cli.recv(100)
  548. assert buf == '*'
  549. raises(timeout, cli.recv, 100)
  550. # test that send() works
  551. count = cli.send('!')
  552. assert count == 1
  553. buf = t.recv(1)
  554. assert buf == '!'
  555. # test that sendall() works
  556. cli.sendall('?')
  557. assert count == 1
  558. buf = t.recv(1)
  559. assert buf == '?'
  560. # test send() timeout
  561. count = 0
  562. try:
  563. while 1:
  564. count += cli.send('foobar' * 70)
  565. except timeout:
  566. pass
  567. t.recv(count)
  568. # test sendall() timeout
  569. try:
  570. while 1:
  571. cli.sendall('foobar' * 70)
  572. except timeout:
  573. pass
  574. # done
  575. cli.close()
  576. t.close()
  577. def test_recv_into(self):
  578. import socket
  579. import array
  580. MSG = 'dupa was here\n'
  581. cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  582. cli.connect(self.serv.getsockname())
  583. conn, addr = self.serv.accept()
  584. buf = buffer(MSG)
  585. conn.send(buf)
  586. buf = array.array('c', ' '*1024)
  587. nbytes = cli.recv_into(buf)
  588. assert nbytes == len(MSG)
  589. msg = buf.tostring()[:len(MSG)]
  590. assert msg == MSG
  591. def test_recvfrom_into(self):
  592. import socket
  593. import array
  594. MSG = 'dupa was here\n'
  595. cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  596. cli.connect(self.serv.getsockname())
  597. conn, addr = self.serv.accept()
  598. buf = buffer(MSG)
  599. conn.send(buf)
  600. buf = array.array('c', ' '*1024)
  601. nbytes, addr = cli.recvfrom_into(buf)
  602. assert nbytes == len(MSG)
  603. msg = buf.tostring()[:len(MSG)]
  604. assert msg == MSG
  605. def test_family(self):
  606. import socket
  607. cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  608. assert cli.family == socket.AF_INET
  609. class AppTestErrno:
  610. def setup_class(cls):
  611. cls.space = space
  612. def test_errno(self):
  613. from socket import socket, AF_INET, SOCK_STREAM, error
  614. import errno
  615. s = socket(AF_INET, SOCK_STREAM)
  616. exc = raises(error, s.accept)
  617. assert isinstance(exc.value, error)
  618. assert isinstance(exc.value, IOError)
  619. # error is EINVAL, or WSAEINVAL on Windows
  620. assert exc.value.errno == getattr(errno, 'WSAEINVAL', errno.EINVAL)
  621. assert isinstance(exc.value.message, str)