PageRenderTime 55ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

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

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