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