PageRenderTime 181ms CodeModel.GetById 94ms app.highlight 81ms RepoModel.GetById 1ms app.codeStats 0ms

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

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