PageRenderTime 75ms CodeModel.GetById 2ms app.highlight 65ms RepoModel.GetById 2ms app.codeStats 0ms

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

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