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