PageRenderTime 103ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

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

https://bitbucket.org/jonathanslenders/pypy
Python | 688 lines | 650 code | 23 blank | 15 comment | 11 complexity | 9299176350424a8ce0c93763947a48d2 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
  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. def test_socket_close_error(self):
  334. import _socket, os
  335. if os.name == 'nt':
  336. skip("Windows sockets are not files")
  337. s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
  338. os.close(s.fileno())
  339. raises(_socket.error, s.close)
  340. def test_socket_connect(self):
  341. import _socket, os
  342. s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
  343. # it would be nice to have a test which works even if there is no
  344. # network connection. However, this one is "good enough" for now. Skip
  345. # it if there is no connection.
  346. try:
  347. s.connect(("www.python.org", 80))
  348. except _socket.gaierror, ex:
  349. skip("GAIError - probably no connection: %s" % str(ex.args))
  350. name = s.getpeername() # Will raise socket.error if not connected
  351. assert name[1] == 80
  352. s.close()
  353. def test_socket_connect_ex(self):
  354. import _socket
  355. s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
  356. # Make sure we get an app-level error, not an interp one.
  357. raises(_socket.gaierror, s.connect_ex, ("wrong.invalid", 80))
  358. s.close()
  359. def test_socket_connect_typeerrors(self):
  360. tests = [
  361. "",
  362. ("80"),
  363. ("80", "80"),
  364. (80, 80),
  365. ]
  366. import _socket
  367. s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
  368. for args in tests:
  369. raises((TypeError, ValueError), s.connect, args)
  370. s.close()
  371. def test_bigport(self):
  372. import _socket
  373. s = _socket.socket()
  374. raises(ValueError, s.connect, ("localhost", 1000000))
  375. raises(ValueError, s.connect, ("localhost", -1))
  376. def test_NtoH(self):
  377. import sys
  378. import _socket as socket
  379. # This just checks that htons etc. are their own inverse,
  380. # when looking at the lower 16 or 32 bits.
  381. sizes = {socket.htonl: 32, socket.ntohl: 32,
  382. socket.htons: 16, socket.ntohs: 16}
  383. for func, size in sizes.items():
  384. mask = (1L<<size) - 1
  385. for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210):
  386. assert i & mask == func(func(i&mask)) & mask
  387. swapped = func(mask)
  388. assert swapped & mask == mask
  389. try:
  390. func(-1)
  391. except (OverflowError, ValueError):
  392. pass
  393. else:
  394. assert False
  395. try:
  396. func(sys.maxint*2+2)
  397. except OverflowError:
  398. pass
  399. else:
  400. assert False
  401. def test_NtoH_overflow(self):
  402. skip("we are not checking for overflowing values yet")
  403. import _socket as socket
  404. # Checks that we cannot give too large values to htons etc.
  405. # Skipped for now; CPython 2.6 is also not consistent.
  406. sizes = {socket.htonl: 32, socket.ntohl: 32,
  407. socket.htons: 16, socket.ntohs: 16}
  408. for func, size in sizes.items():
  409. try:
  410. func(1L << size)
  411. except OverflowError:
  412. pass
  413. else:
  414. assert False
  415. def test_newsocket(self):
  416. import socket
  417. s = socket.socket()
  418. def test_getsetsockopt(self):
  419. import _socket as socket
  420. import struct
  421. # A socket sould start with reuse == 0
  422. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  423. reuse = s.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
  424. assert reuse == 0
  425. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  426. reuse = s.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
  427. assert reuse != 0
  428. # String case
  429. intsize = struct.calcsize('i')
  430. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  431. reusestr = s.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,
  432. intsize)
  433. (reuse,) = struct.unpack('i', reusestr)
  434. assert reuse == 0
  435. reusestr = struct.pack('i', 1)
  436. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, reusestr)
  437. reusestr = s.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,
  438. intsize)
  439. (reuse,) = struct.unpack('i', reusestr)
  440. assert reuse != 0
  441. def test_socket_ioctl(self):
  442. import _socket, sys
  443. if sys.platform != 'win32':
  444. skip("win32 only")
  445. assert hasattr(_socket.socket, 'ioctl')
  446. assert hasattr(_socket, 'SIO_RCVALL')
  447. assert hasattr(_socket, 'RCVALL_ON')
  448. assert hasattr(_socket, 'RCVALL_OFF')
  449. assert hasattr(_socket, 'SIO_KEEPALIVE_VALS')
  450. s = _socket.socket()
  451. raises(ValueError, s.ioctl, -1, None)
  452. s.ioctl(_socket.SIO_KEEPALIVE_VALS, (1, 100, 100))
  453. def test_dup(self):
  454. import _socket as socket
  455. if not hasattr(socket.socket, 'dup'):
  456. skip('No dup() on this platform')
  457. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  458. s.bind(('localhost', 0))
  459. s2 = s.dup()
  460. assert s.fileno() != s2.fileno()
  461. assert s.getsockname() == s2.getsockname()
  462. def test_buffer_or_unicode(self):
  463. # Test that send/sendall/sendto accept a buffer or a unicode as arg
  464. import _socket, os
  465. s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM, 0)
  466. # XXX temporarily we use python.org to test, will have more robust tests
  467. # in the absence of a network connection later when more parts of the
  468. # socket API are implemented. Currently skip the test if there is no
  469. # connection.
  470. try:
  471. s.connect(("www.python.org", 80))
  472. except _socket.gaierror, ex:
  473. skip("GAIError - probably no connection: %s" % str(ex.args))
  474. s.send(buffer(''))
  475. s.sendall(buffer(''))
  476. s.send(u'')
  477. s.sendall(u'')
  478. raises(UnicodeEncodeError, s.send, u'\xe9')
  479. s.close()
  480. s = _socket.socket(_socket.AF_INET, _socket.SOCK_DGRAM, 0)
  481. s.sendto(buffer(''), ('localhost', 9)) # Send to discard port.
  482. s.close()
  483. def test_unix_socket_connect(self):
  484. import _socket, os
  485. if not hasattr(_socket, 'AF_UNIX'):
  486. skip('AF_UNIX not supported.')
  487. oldcwd = os.getcwd()
  488. os.chdir(self.udir)
  489. try:
  490. sockpath = 'app_test_unix_socket_connect'
  491. serversock = _socket.socket(_socket.AF_UNIX)
  492. serversock.bind(sockpath)
  493. serversock.listen(1)
  494. clientsock = _socket.socket(_socket.AF_UNIX)
  495. clientsock.connect(sockpath)
  496. s, addr = serversock.accept()
  497. assert not addr
  498. s.send('X')
  499. data = clientsock.recv(100)
  500. assert data == 'X'
  501. clientsock.send('Y')
  502. data = s.recv(100)
  503. assert data == 'Y'
  504. clientsock.close()
  505. s.close()
  506. finally:
  507. os.chdir(oldcwd)
  508. class AppTestSocketTCP:
  509. def setup_class(cls):
  510. cls.space = space
  511. HOST = 'localhost'
  512. def setup_method(self, method):
  513. w_HOST = space.wrap(self.HOST)
  514. self.w_serv = space.appexec([w_socket, w_HOST],
  515. '''(_socket, HOST):
  516. serv = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
  517. serv.bind((HOST, 0))
  518. serv.listen(1)
  519. return serv
  520. ''')
  521. def teardown_method(self, method):
  522. if hasattr(self, 'w_serv'):
  523. space.appexec([self.w_serv], '(serv): serv.close()')
  524. self.w_serv = None
  525. def test_timeout(self):
  526. from _socket import timeout
  527. def raise_timeout():
  528. self.serv.settimeout(1.0)
  529. self.serv.accept()
  530. raises(timeout, raise_timeout)
  531. def test_timeout_zero(self):
  532. from _socket import error
  533. def raise_error():
  534. self.serv.settimeout(0.0)
  535. foo = self.serv.accept()
  536. raises(error, raise_error)
  537. def test_recv_send_timeout(self):
  538. from _socket import socket, timeout
  539. cli = socket()
  540. cli.connect(self.serv.getsockname())
  541. t, addr = self.serv.accept()
  542. cli.settimeout(1.0)
  543. # test recv() timeout
  544. t.send('*')
  545. buf = cli.recv(100)
  546. assert buf == '*'
  547. raises(timeout, cli.recv, 100)
  548. # test that send() works
  549. count = cli.send('!')
  550. assert count == 1
  551. buf = t.recv(1)
  552. assert buf == '!'
  553. # test that sendall() works
  554. cli.sendall('?')
  555. assert count == 1
  556. buf = t.recv(1)
  557. assert buf == '?'
  558. # test send() timeout
  559. count = 0
  560. try:
  561. while 1:
  562. count += cli.send('foobar' * 70)
  563. except timeout:
  564. pass
  565. t.recv(count)
  566. # test sendall() timeout
  567. try:
  568. while 1:
  569. cli.sendall('foobar' * 70)
  570. except timeout:
  571. pass
  572. # done
  573. cli.close()
  574. t.close()
  575. def test_recv_into(self):
  576. import socket
  577. import array
  578. MSG = 'dupa was here\n'
  579. cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  580. cli.connect(self.serv.getsockname())
  581. conn, addr = self.serv.accept()
  582. buf = buffer(MSG)
  583. conn.send(buf)
  584. buf = array.array('c', ' '*1024)
  585. nbytes = cli.recv_into(buf)
  586. assert nbytes == len(MSG)
  587. msg = buf.tostring()[:len(MSG)]
  588. assert msg == MSG
  589. def test_recvfrom_into(self):
  590. import socket
  591. import array
  592. MSG = 'dupa was here\n'
  593. cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  594. cli.connect(self.serv.getsockname())
  595. conn, addr = self.serv.accept()
  596. buf = buffer(MSG)
  597. conn.send(buf)
  598. buf = array.array('c', ' '*1024)
  599. nbytes, addr = cli.recvfrom_into(buf)
  600. assert nbytes == len(MSG)
  601. msg = buf.tostring()[:len(MSG)]
  602. assert msg == MSG
  603. def test_family(self):
  604. import socket
  605. cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  606. assert cli.family == socket.AF_INET
  607. class AppTestErrno:
  608. def setup_class(cls):
  609. cls.space = space
  610. def test_errno(self):
  611. from socket import socket, AF_INET, SOCK_STREAM, error
  612. import errno
  613. s = socket(AF_INET, SOCK_STREAM)
  614. exc = raises(error, s.accept)
  615. assert isinstance(exc.value, error)
  616. assert isinstance(exc.value, IOError)
  617. # error is EINVAL, or WSAEINVAL on Windows
  618. assert exc.value.errno == getattr(errno, 'WSAEINVAL', errno.EINVAL)
  619. assert isinstance(exc.value.message, str)