/Lib/test/test_socket.py
Python | 2252 lines | 2003 code | 152 blank | 97 comment | 114 complexity | 628428ee780201490e55b7f1c8f61152 MD5 | raw file
Large files files are truncated, but you can click here to view the full file
1import java 2 3import unittest 4from test import test_support 5 6import errno 7import jarray 8import Queue 9import platform 10import select 11import socket 12import struct 13import sys 14import time 15import thread, threading 16from weakref import proxy 17from StringIO import StringIO 18 19PORT = 50100 20HOST = 'localhost' 21MSG = 'Michael Gilfix was here\n' 22EIGHT_BIT_MSG = 'Bh\xed Al\xe1in \xd3 Cinn\xe9ide anseo\n' 23os_name = platform.java_ver()[3][0] 24is_bsd = os_name == 'Mac OS X' or 'BSD' in os_name 25is_solaris = os_name == 'SunOS' 26 27class SocketTCPTest(unittest.TestCase): 28 29 HOST = HOST 30 PORT = PORT 31 32 def setUp(self): 33 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 34 self.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 35 self.serv.bind((self.HOST, self.PORT)) 36 self.serv.listen(1) 37 38 def tearDown(self): 39 self.serv.close() 40 self.serv = None 41 42class SocketUDPTest(unittest.TestCase): 43 44 HOST = HOST 45 PORT = PORT 46 47 def setUp(self): 48 self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 49 self.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 50 self.serv.bind((self.HOST, self.PORT)) 51 52 def tearDown(self): 53 self.serv.close() 54 self.serv = None 55 56class ThreadableTest: 57 """Threadable Test class 58 59 The ThreadableTest class makes it easy to create a threaded 60 client/server pair from an existing unit test. To create a 61 new threaded class from an existing unit test, use multiple 62 inheritance: 63 64 class NewClass (OldClass, ThreadableTest): 65 pass 66 67 This class defines two new fixture functions with obvious 68 purposes for overriding: 69 70 clientSetUp () 71 clientTearDown () 72 73 Any new test functions within the class must then define 74 tests in pairs, where the test name is preceeded with a 75 '_' to indicate the client portion of the test. Ex: 76 77 def testFoo(self): 78 # Server portion 79 80 def _testFoo(self): 81 # Client portion 82 83 Any exceptions raised by the clients during their tests 84 are caught and transferred to the main thread to alert 85 the testing framework. 86 87 Note, the server setup function cannot call any blocking 88 functions that rely on the client thread during setup, 89 unless serverExplicityReady() is called just before 90 the blocking call (such as in setting up a client/server 91 connection and performing the accept() in setUp(). 92 """ 93 94 def __init__(self): 95 # Swap the true setup function 96 self.__setUp = self.setUp 97 self.__tearDown = self.tearDown 98 self.setUp = self._setUp 99 self.tearDown = self._tearDown 100 101 def serverExplicitReady(self): 102 """This method allows the server to explicitly indicate that 103 it wants the client thread to proceed. This is useful if the 104 server is about to execute a blocking routine that is 105 dependent upon the client thread during its setup routine.""" 106 self.server_ready.set() 107 108 def _setUp(self): 109 self.server_ready = threading.Event() 110 self.client_ready = threading.Event() 111 self.done = threading.Event() 112 self.queue = Queue.Queue(1) 113 114 # Do some munging to start the client test. 115 methodname = self.id() 116 i = methodname.rfind('.') 117 methodname = methodname[i+1:] 118 self.test_method_name = methodname 119 test_method = getattr(self, '_' + methodname) 120 self.client_thread = thread.start_new_thread( 121 self.clientRun, (test_method,)) 122 123 self.__setUp() 124 if not self.server_ready.isSet(): 125 self.server_ready.set() 126 self.client_ready.wait() 127 128 def _tearDown(self): 129 self.done.wait() 130 self.__tearDown() 131 132 if not self.queue.empty(): 133 msg = self.queue.get() 134 self.fail(msg) 135 136 def clientRun(self, test_func): 137 self.server_ready.wait() 138 self.client_ready.set() 139 self.clientSetUp() 140 if not callable(test_func): 141 raise TypeError, "test_func must be a callable function" 142 try: 143 test_func() 144 except Exception, strerror: 145 self.queue.put(strerror) 146 self.clientTearDown() 147 148 def clientSetUp(self): 149 raise NotImplementedError, "clientSetUp must be implemented." 150 151 def clientTearDown(self): 152 self.done.set() 153 if sys.platform[:4] != 'java': 154 # This causes the whole process to exit on jython 155 # Probably related to problems with daemon status of threads 156 thread.exit() 157 158class ThreadedTCPSocketTest(SocketTCPTest, ThreadableTest): 159 160 def __init__(self, methodName='runTest'): 161 SocketTCPTest.__init__(self, methodName=methodName) 162 ThreadableTest.__init__(self) 163 164 def clientSetUp(self): 165 self.cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 166 self.cli.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 167 168 def clientTearDown(self): 169 self.cli.close() 170 self.cli = None 171 ThreadableTest.clientTearDown(self) 172 173class ThreadedUDPSocketTest(SocketUDPTest, ThreadableTest): 174 175 def __init__(self, methodName='runTest'): 176 SocketUDPTest.__init__(self, methodName=methodName) 177 ThreadableTest.__init__(self) 178 179 def clientSetUp(self): 180 self.cli = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 181 self.cli.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 182 183class SocketConnectedTest(ThreadedTCPSocketTest): 184 185 def __init__(self, methodName='runTest'): 186 ThreadedTCPSocketTest.__init__(self, methodName=methodName) 187 188 def setUp(self): 189 ThreadedTCPSocketTest.setUp(self) 190 # Indicate explicitly we're ready for the client thread to 191 # proceed and then perform the blocking call to accept 192 self.serverExplicitReady() 193 conn, addr = self.serv.accept() 194 self.cli_conn = conn 195 196 def tearDown(self): 197 self.cli_conn.close() 198 self.cli_conn = None 199 ThreadedTCPSocketTest.tearDown(self) 200 201 def clientSetUp(self): 202 ThreadedTCPSocketTest.clientSetUp(self) 203 self.cli.connect((self.HOST, self.PORT)) 204 self.serv_conn = self.cli 205 206 def clientTearDown(self): 207 self.serv_conn.close() 208 self.serv_conn = None 209 ThreadedTCPSocketTest.clientTearDown(self) 210 211class SocketPairTest(unittest.TestCase, ThreadableTest): 212 213 def __init__(self, methodName='runTest'): 214 unittest.TestCase.__init__(self, methodName=methodName) 215 ThreadableTest.__init__(self) 216 217 def setUp(self): 218 self.serv, self.cli = socket.socketpair() 219 220 def tearDown(self): 221 self.serv.close() 222 self.serv = None 223 224 def clientSetUp(self): 225 pass 226 227 def clientTearDown(self): 228 self.cli.close() 229 self.cli = None 230 ThreadableTest.clientTearDown(self) 231 232 233####################################################################### 234## Begin Tests 235 236class GeneralModuleTests(unittest.TestCase): 237 238 def test_weakref(self): 239 if sys.platform[:4] == 'java': return 240 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 241 p = proxy(s) 242 self.assertEqual(p.fileno(), s.fileno()) 243 s.close() 244 s = None 245 try: 246 p.fileno() 247 except ReferenceError: 248 pass 249 else: 250 self.fail('Socket proxy still exists') 251 252 def testSocketError(self): 253 # Testing socket module exceptions 254 def raise_error(*args, **kwargs): 255 raise socket.error 256 def raise_herror(*args, **kwargs): 257 raise socket.herror 258 def raise_gaierror(*args, **kwargs): 259 raise socket.gaierror 260 self.failUnlessRaises(socket.error, raise_error, 261 "Error raising socket exception.") 262 self.failUnlessRaises(socket.error, raise_herror, 263 "Error raising socket exception.") 264 self.failUnlessRaises(socket.error, raise_gaierror, 265 "Error raising socket exception.") 266 267 def testCrucialConstants(self): 268 # Testing for mission critical constants 269 socket.AF_INET 270 socket.SOCK_STREAM 271 socket.SOCK_DGRAM 272 socket.SOCK_RAW 273 socket.SOCK_RDM 274 socket.SOCK_SEQPACKET 275 socket.SOL_SOCKET 276 socket.SO_REUSEADDR 277 278 def testConstantToNameMapping(self): 279 # Testing for mission critical constants 280 for name in ['SOL_SOCKET', 'IPPROTO_TCP', 'IPPROTO_UDP', 'SO_BROADCAST', 'SO_KEEPALIVE', 'TCP_NODELAY', 'SO_ACCEPTCONN', 'SO_DEBUG']: 281 self.failUnlessEqual(socket._constant_to_name(getattr(socket, name)), name) 282 283 def testHostnameRes(self): 284 # Testing hostname resolution mechanisms 285 hostname = socket.gethostname() 286 self.assert_(isinstance(hostname, str)) 287 try: 288 ip = socket.gethostbyname(hostname) 289 self.assert_(isinstance(ip, str)) 290 except socket.error: 291 # Probably name lookup wasn't set up right; skip this test 292 self.fail("Probably name lookup wasn't set up right; skip testHostnameRes.gethostbyname") 293 return 294 self.assert_(ip.find('.') >= 0, "Error resolving host to ip.") 295 try: 296 hname, aliases, ipaddrs = socket.gethostbyaddr(ip) 297 self.assert_(isinstance(hname, str)) 298 for hosts in aliases, ipaddrs: 299 self.assert_(all(isinstance(host, str) for host in hosts)) 300 except socket.error: 301 # Probably a similar problem as above; skip this test 302 self.fail("Probably name lookup wasn't set up right; skip testHostnameRes.gethostbyaddr") 303 return 304 all_host_names = [hostname, hname] + aliases 305 fqhn = socket.getfqdn() 306 self.assert_(isinstance(fqhn, str)) 307 if not fqhn in all_host_names: 308 self.fail("Error testing host resolution mechanisms.") 309 310 def testRefCountGetNameInfo(self): 311 # Testing reference count for getnameinfo 312 import sys 313 if hasattr(sys, "getrefcount"): 314 try: 315 # On some versions, this loses a reference 316 orig = sys.getrefcount(__name__) 317 socket.getnameinfo(__name__,0) 318 except SystemError: 319 if sys.getrefcount(__name__) <> orig: 320 self.fail("socket.getnameinfo loses a reference") 321 322 def testInterpreterCrash(self): 323 if sys.platform[:4] == 'java': return 324 # Making sure getnameinfo doesn't crash the interpreter 325 try: 326 # On some versions, this crashes the interpreter. 327 socket.getnameinfo(('x', 0, 0, 0), 0) 328 except socket.error: 329 pass 330 331# Need to implement binary AND for ints and longs 332 333 def testNtoH(self): 334 if sys.platform[:4] == 'java': return # problems with int & long 335 # This just checks that htons etc. are their own inverse, 336 # when looking at the lower 16 or 32 bits. 337 sizes = {socket.htonl: 32, socket.ntohl: 32, 338 socket.htons: 16, socket.ntohs: 16} 339 for func, size in sizes.items(): 340 mask = (1L<<size) - 1 341 for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210): 342 self.assertEqual(i & mask, func(func(i&mask)) & mask) 343 344 swapped = func(mask) 345 self.assertEqual(swapped & mask, mask) 346 self.assertRaises(OverflowError, func, 1L<<34) 347 348 def testGetServBy(self): 349 eq = self.assertEqual 350 # Find one service that exists, then check all the related interfaces. 351 # I've ordered this by protocols that have both a tcp and udp 352 # protocol, at least for modern Linuxes. 353 if sys.platform in ('linux2', 'freebsd4', 'freebsd5', 'freebsd6', 354 'darwin') or is_bsd: 355 # avoid the 'echo' service on this platform, as there is an 356 # assumption breaking non-standard port/protocol entry 357 services = ('daytime', 'qotd', 'domain') 358 else: 359 services = ('echo', 'daytime', 'domain') 360 for service in services: 361 try: 362 port = socket.getservbyname(service, 'tcp') 363 break 364 except socket.error: 365 pass 366 else: 367 raise socket.error 368 # Try same call with optional protocol omitted 369 port2 = socket.getservbyname(service) 370 eq(port, port2) 371 # Try udp, but don't barf it it doesn't exist 372 try: 373 udpport = socket.getservbyname(service, 'udp') 374 except socket.error: 375 udpport = None 376 else: 377 eq(udpport, port) 378 # Now make sure the lookup by port returns the same service name 379 eq(socket.getservbyport(port2), service) 380 eq(socket.getservbyport(port, 'tcp'), service) 381 if udpport is not None: 382 eq(socket.getservbyport(udpport, 'udp'), service) 383 384 def testGetServByExceptions(self): 385 # First getservbyname 386 try: 387 result = socket.getservbyname("nosuchservice") 388 except socket.error: 389 pass 390 except Exception, x: 391 self.fail("getservbyname raised wrong exception for non-existent service: %s" % str(x)) 392 else: 393 self.fail("getservbyname failed to raise exception for non-existent service: %s" % str(result)) 394 395 # Now getservbyport 396 try: 397 result = socket.getservbyport(55555) 398 except socket.error: 399 pass 400 except Exception, x: 401 self.fail("getservbyport raised wrong exception for unknown port: %s" % str(x)) 402 else: 403 self.fail("getservbyport failed to raise exception for unknown port: %s" % str(result)) 404 405 def testGetProtoByName(self): 406 self.failUnlessEqual(socket.IPPROTO_TCP, socket.getprotobyname("tcp")) 407 self.failUnlessEqual(socket.IPPROTO_UDP, socket.getprotobyname("udp")) 408 try: 409 result = socket.getprotobyname("nosuchproto") 410 except socket.error: 411 pass 412 except Exception, x: 413 self.fail("getprotobyname raised wrong exception for unknown protocol: %s" % str(x)) 414 else: 415 self.fail("getprotobyname failed to raise exception for unknown protocol: %s" % str(result)) 416 417 def testDefaultTimeout(self): 418 # Testing default timeout 419 # The default timeout should initially be None 420 self.assertEqual(socket.getdefaulttimeout(), None) 421 s = socket.socket() 422 self.assertEqual(s.gettimeout(), None) 423 s.close() 424 425 # Set the default timeout to 10, and see if it propagates 426 socket.setdefaulttimeout(10) 427 self.assertEqual(socket.getdefaulttimeout(), 10) 428 s = socket.socket() 429 self.assertEqual(s.gettimeout(), 10) 430 s.close() 431 432 # Reset the default timeout to None, and see if it propagates 433 socket.setdefaulttimeout(None) 434 self.assertEqual(socket.getdefaulttimeout(), None) 435 s = socket.socket() 436 self.assertEqual(s.gettimeout(), None) 437 s.close() 438 439 # Check that setting it to an invalid value raises ValueError 440 self.assertRaises(ValueError, socket.setdefaulttimeout, -1) 441 442 # Check that setting it to an invalid type raises TypeError 443 self.assertRaises(TypeError, socket.setdefaulttimeout, "spam") 444 445 def testIPv4toString(self): 446 if not hasattr(socket, 'inet_pton'): 447 return # No inet_pton() on this platform 448 from socket import inet_aton as f, inet_pton, AF_INET 449 g = lambda a: inet_pton(AF_INET, a) 450 451 self.assertEquals('\x00\x00\x00\x00', f('0.0.0.0')) 452 self.assertEquals('\xff\x00\xff\x00', f('255.0.255.0')) 453 self.assertEquals('\xaa\xaa\xaa\xaa', f('170.170.170.170')) 454 self.assertEquals('\x01\x02\x03\x04', f('1.2.3.4')) 455 456 self.assertEquals('\x00\x00\x00\x00', g('0.0.0.0')) 457 self.assertEquals('\xff\x00\xff\x00', g('255.0.255.0')) 458 self.assertEquals('\xaa\xaa\xaa\xaa', g('170.170.170.170')) 459 460 def testIPv6toString(self): 461 if not hasattr(socket, 'inet_pton'): 462 return # No inet_pton() on this platform 463 try: 464 from socket import inet_pton, AF_INET6, has_ipv6 465 if not has_ipv6: 466 return 467 except ImportError: 468 return 469 f = lambda a: inet_pton(AF_INET6, a) 470 471 self.assertEquals('\x00' * 16, f('::')) 472 self.assertEquals('\x00' * 16, f('0::0')) 473 self.assertEquals('\x00\x01' + '\x00' * 14, f('1::')) 474 self.assertEquals( 475 '\x45\xef\x76\xcb\x00\x1a\x56\xef\xaf\xeb\x0b\xac\x19\x24\xae\xae', 476 f('45ef:76cb:1a:56ef:afeb:bac:1924:aeae') 477 ) 478 479 def test_inet_pton_exceptions(self): 480 if not hasattr(socket, 'inet_pton'): 481 return # No inet_pton() on this platform 482 483 try: 484 socket.inet_pton(socket.AF_UNSPEC, "doesntmatter") 485 except socket.error, se: 486 self.failUnlessEqual(se[0], errno.EAFNOSUPPORT) 487 except Exception, x: 488 self.fail("inet_pton raised wrong exception for incorrect address family AF_UNSPEC: %s" % str(x)) 489 490 try: 491 socket.inet_pton(socket.AF_INET, "1.2.3.") 492 except socket.error, se: 493 pass 494 except Exception, x: 495 self.fail("inet_pton raised wrong exception for invalid AF_INET address: %s" % str(x)) 496 497 try: 498 socket.inet_pton(socket.AF_INET6, ":::") 499 except socket.error, se: 500 pass 501 except Exception, x: 502 self.fail("inet_pton raised wrong exception for invalid AF_INET6 address: %s" % str(x)) 503 504 def testStringToIPv4(self): 505 if not hasattr(socket, 'inet_ntop'): 506 return # No inet_ntop() on this platform 507 from socket import inet_ntoa as f, inet_ntop, AF_INET 508 g = lambda a: inet_ntop(AF_INET, a) 509 510 self.assertEquals('1.0.1.0', f('\x01\x00\x01\x00')) 511 self.assertEquals('170.85.170.85', f('\xaa\x55\xaa\x55')) 512 self.assertEquals('255.255.255.255', f('\xff\xff\xff\xff')) 513 self.assertEquals('1.2.3.4', f('\x01\x02\x03\x04')) 514 515 self.assertEquals('1.0.1.0', g('\x01\x00\x01\x00')) 516 self.assertEquals('170.85.170.85', g('\xaa\x55\xaa\x55')) 517 self.assertEquals('255.255.255.255', g('\xff\xff\xff\xff')) 518 519 def testStringToIPv6(self): 520 if not hasattr(socket, 'inet_ntop'): 521 return # No inet_ntop() on this platform 522 try: 523 from socket import inet_ntop, AF_INET6, has_ipv6 524 if not has_ipv6: 525 return 526 except ImportError: 527 return 528 f = lambda a: inet_ntop(AF_INET6, a) 529 530# self.assertEquals('::', f('\x00' * 16)) 531# self.assertEquals('::1', f('\x00' * 15 + '\x01')) 532 # java.net.InetAddress always return the full unabbreviated form 533 self.assertEquals('0:0:0:0:0:0:0:0', f('\x00' * 16)) 534 self.assertEquals('0:0:0:0:0:0:0:1', f('\x00' * 15 + '\x01')) 535 self.assertEquals( 536 'aef:b01:506:1001:ffff:9997:55:170', 537 f('\x0a\xef\x0b\x01\x05\x06\x10\x01\xff\xff\x99\x97\x00\x55\x01\x70') 538 ) 539 540 def test_inet_ntop_exceptions(self): 541 if not hasattr(socket, 'inet_ntop'): 542 return # No inet_ntop() on this platform 543 valid_address = '\x01\x01\x01\x01' 544 invalid_address = '\x01\x01\x01\x01\x01' 545 546 try: 547 socket.inet_ntop(socket.AF_UNSPEC, valid_address) 548 except ValueError, v: 549 pass 550 except Exception, x: 551 self.fail("inet_ntop raised wrong exception for incorrect address family AF_UNSPEC: %s" % str(x)) 552 553 try: 554 socket.inet_ntop(socket.AF_INET, invalid_address) 555 except ValueError, v: 556 pass 557 except Exception, x: 558 self.fail("inet_ntop raised wrong exception for invalid AF_INET address: %s" % str(x)) 559 560 try: 561 socket.inet_ntop(socket.AF_INET6, invalid_address) 562 except ValueError, v: 563 pass 564 except Exception, x: 565 self.fail("inet_ntop raised wrong exception for invalid AF_INET address: %s" % str(x)) 566 567 # XXX The following don't test module-level functionality... 568 569 def testSockName(self): 570 # Testing getsockname() 571 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 572 sock.bind(("0.0.0.0", PORT+1)) 573 name = sock.getsockname() 574 self.assertEqual(name, ("0.0.0.0", PORT+1)) 575 576 def testSockAttributes(self): 577 # Testing required attributes 578 for family in [socket.AF_INET, socket.AF_INET6]: 579 for sock_type in [socket.SOCK_STREAM, socket.SOCK_DGRAM]: 580 s = socket.socket(family, sock_type) 581 self.assertEqual(s.family, family) 582 self.assertEqual(s.type, sock_type) 583 if sock_type == socket.SOCK_STREAM: 584 self.assertEqual(s.proto, socket.IPPROTO_TCP) 585 else: 586 self.assertEqual(s.proto, socket.IPPROTO_UDP) 587 588 def testGetSockOpt(self): 589 # Testing getsockopt() 590 # We know a socket should start without reuse==0 591 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 592 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) 593 self.failIf(reuse != 0, "initial mode is reuse") 594 595 def testSetSockOpt(self): 596 # Testing setsockopt() 597 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 598 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 599 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) 600 self.failIf(reuse == 0, "failed to set reuse mode") 601 602 def testSendAfterClose(self): 603 # testing send() after close() with timeout 604 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 605 sock.settimeout(1) 606 sock.close() 607 self.assertRaises(socket.error, sock.send, "spam") 608 609class IPAddressTests(unittest.TestCase): 610 611 def testValidIpV4Addresses(self): 612 for a in [ 613 "0.0.0.1", 614 "1.0.0.1", 615 "127.0.0.1", 616 "255.12.34.56", 617 "255.255.255.255", 618 ]: 619 self.failUnless(socket.is_ipv4_address(a), "is_ipv4_address failed for valid IPV4 address '%s'" % a) 620 self.failUnless(socket.is_ip_address(a), "is_ip_address failed for valid IPV4 address '%s'" % a) 621 622 def testInvalidIpV4Addresses(self): 623 for a in [ 624 "99.2", 625 "99.2.4", 626 "-10.1.2.3", 627 "256.0.0.0", 628 "0.256.0.0", 629 "0.0.256.0", 630 "0.0.0.256", 631 "255.24.x.100", 632 "255.24.-1.128", 633 "255.24.-1.128.", 634 "255.0.0.999", 635 ]: 636 self.failUnless(not socket.is_ipv4_address(a), "not is_ipv4_address failed for invalid IPV4 address '%s'" % a) 637 self.failUnless(not socket.is_ip_address(a), "not is_ip_address failed for invalid IPV4 address '%s'" % a) 638 639 def testValidIpV6Addresses(self): 640 for a in [ 641 "::", 642 "::1", 643 "fe80::1", 644 "::192.168.1.1", 645 "0:0:0:0:0:0:0:0", 646 "1080::8:800:2C:4A", 647 "FEC0:0:0:0:0:0:0:1", 648 "::FFFF:192.168.1.1", 649 "abcd:ef:111:f123::1", 650 "1138:0:0:0:8:80:800:417A", 651 "fecc:face::b00c:f001:fedc:fedd", 652 "CaFe:BaBe:dEAd:BeeF:12:345:6789:abcd", 653 ]: 654 self.failUnless(socket.is_ipv6_address(a), "is_ipv6_address failed for valid IPV6 address '%s'" % a) 655 self.failUnless(socket.is_ip_address(a), "is_ip_address failed for valid IPV6 address '%s'" % a) 656 657 def testInvalidIpV6Addresses(self): 658 for a in [ 659 "2001:db8:::192.0.2.1", # from RFC 5954 660 "CaFe:BaBe:dEAd:BeeF:12:345:6789:abcd:", 661 "CaFe:BaBe:dEAd:BeeF:12:345:6789:abcd:ef", 662 "CaFFe:1a77e:dEAd:BeeF:12:345:6789:abcd", 663 ]: 664 self.failUnless(not socket.is_ipv6_address(a), "not is_ipv6_address failed for invalid IPV6 address '%s'" % a) 665 self.failUnless(not socket.is_ip_address(a), "not is_ip_address failed for invalid IPV6 address '%s'" % a) 666 667 def testRFC5952(self): 668 for a in [ 669 "2001:db8::", 670 "2001:db8::1", 671 "2001:db8:0::1", 672 "2001:db8:0:0::1", 673 "2001:db8:0:0:0::1", 674 "2001:DB8:0:0:1::1", 675 "2001:db8:0:0:1::1", 676 "2001:db8::1:0:0:1", 677 "2001:0db8::1:0:0:1", 678 "2001:db8::0:1:0:0:1", 679 "2001:db8:0:0:1:0:0:1", 680 "2001:db8:0000:0:1::1", 681 "2001:db8::aaaa:0:0:1", 682 "2001:db8:0:0:aaaa::1", 683 "2001:0db8:0:0:1:0:0:1", 684 "2001:db8:aaaa:bbbb:cccc:dddd::1", 685 "2001:db8:aaaa:bbbb:cccc:dddd:0:1", 686 "2001:db8:aaaa:bbbb:cccc:dddd:eeee:1", 687 "2001:db8:aaaa:bbbb:cccc:dddd:eeee:01", 688 "2001:db8:aaaa:bbbb:cccc:dddd:eeee:001", 689 "2001:db8:aaaa:bbbb:cccc:dddd:eeee:0001", 690 "2001:db8:aaaa:bbbb:cccc:dddd:eeee:aaaa", 691 "2001:db8:aaaa:bbbb:cccc:dddd:eeee:AAAA", 692 "2001:db8:aaaa:bbbb:cccc:dddd:eeee:AaAa", 693 ]: 694 self.failUnless(socket.is_ipv6_address(a), "is_ipv6_address failed for valid RFC 5952 IPV6 address '%s'" % a) 695 self.failUnless(socket.is_ip_address(a), "is_ip_address failed for valid RFC 5952 IPV6 address '%s'" % a) 696 697class TestSocketOptions(unittest.TestCase): 698 699 def setUp(self): 700 self.test_udp = self.test_tcp_client = self.test_tcp_server = 0 701 702 def _testSetAndGetOption(self, sock, level, option, values): 703 for expected_value in values: 704 sock.setsockopt(level, option, expected_value) 705 retrieved_value = sock.getsockopt(level, option) 706 msg = "Retrieved option(%s, %s) value %s != %s(value set)" % (level, option, retrieved_value, expected_value) 707 if option == socket.SO_RCVBUF: 708 self.assert_(retrieved_value >= expected_value, msg) 709 else: 710 self.failUnlessEqual(retrieved_value, expected_value, msg) 711 712 def _testUDPOption(self, level, option, values): 713 try: 714 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 715 self._testSetAndGetOption(sock, level, option, values) 716 # now bind the socket i.e. cause the implementation socket to be created 717 sock.bind( (HOST, PORT) ) 718 self.failUnlessEqual(sock.getsockopt(level, option), values[-1], \ 719 "Option value '(%s, %s)'='%s' did not propagate to implementation socket" % (level, option, values[-1]) ) 720 self._testSetAndGetOption(sock, level, option, values) 721 finally: 722 sock.close() 723 724 def _testTCPClientOption(self, level, option, values): 725 sock = None 726 try: 727 # First listen on a server socket, so that the connection won't be refused. 728 server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 729 server_sock.bind( (HOST, PORT) ) 730 server_sock.listen(50) 731 # Now do the tests 732 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 733 self._testSetAndGetOption(sock, level, option, values) 734 # now connect the socket i.e. cause the implementation socket to be created 735 # First bind, so that the SO_REUSEADDR setting propagates 736 sock.bind( (HOST, PORT+1) ) 737 sock.connect( (HOST, PORT) ) 738 msg = "Option value '%s'='%s' did not propagate to implementation socket" % (option, values[-1]) 739 if option in (socket.SO_RCVBUF, socket.SO_SNDBUF): 740 # NOTE: there's no guarantee that bufsize will be the 741 # exact setsockopt value, particularly after 742 # establishing a connection. seems it will be *at least* 743 # the values we test (which are rather small) on 744 # BSDs. 745 self.assert_(sock.getsockopt(level, option) >= values[-1], msg) 746 else: 747 self.failUnlessEqual(sock.getsockopt(level, option), values[-1], msg) 748 self._testSetAndGetOption(sock, level, option, values) 749 finally: 750 server_sock.close() 751 if sock: 752 sock.close() 753 754 def _testTCPServerOption(self, level, option, values): 755 try: 756 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 757 self._testSetAndGetOption(sock, level, option, values) 758 # now bind and listen on the socket i.e. cause the implementation socket to be created 759 sock.bind( (HOST, PORT) ) 760 sock.listen(50) 761 msg = "Option value '(%s,%s)'='%s' did not propagate to implementation socket" % (level, option, values[-1]) 762 if is_solaris and option == socket.SO_RCVBUF: 763 # NOTE: see similar bsd/solaris workaround above 764 self.assert_(sock.getsockopt(level, option) >= values[-1], msg) 765 else: 766 self.failUnlessEqual(sock.getsockopt(level, option), values[-1], msg) 767 self._testSetAndGetOption(sock, level, option, values) 768 finally: 769 sock.close() 770 771 def _testOption(self, level, option, values): 772 for flag, func in [ 773 (self.test_udp, self._testUDPOption), 774 (self.test_tcp_server, self._testTCPServerOption), 775 (self.test_tcp_client, self._testTCPClientOption), 776 ]: 777 if flag: 778 func(level, option, values) 779 else: 780 try: 781 func(level, option, values) 782 except socket.error, se: 783 self.failUnlessEqual(se[0], errno.ENOPROTOOPT, "Wrong errno from unsupported option exception: %d" % se[0]) 784 except Exception, x: 785 self.fail("Wrong exception raised from unsupported option: %s" % str(x)) 786 else: 787 self.fail("Setting unsupported option should have raised an exception") 788 789class TestSupportedOptions(TestSocketOptions): 790 791 def testSO_BROADCAST(self): 792 self.test_udp = 1 793 self._testOption(socket.SOL_SOCKET, socket.SO_BROADCAST, [0, 1]) 794 795 def testSO_KEEPALIVE(self): 796 self.test_tcp_client = 1 797 self._testOption(socket.SOL_SOCKET, socket.SO_KEEPALIVE, [0, 1]) 798 799 def testSO_LINGER(self): 800 self.test_tcp_client = 1 801 off = struct.pack('ii', 0, 0) 802 on_2_seconds = struct.pack('ii', 1, 2) 803 self._testOption(socket.SOL_SOCKET, socket.SO_LINGER, [off, on_2_seconds]) 804 805 def testSO_OOBINLINE(self): 806 self.test_tcp_client = 1 807 self._testOption(socket.SOL_SOCKET, socket.SO_OOBINLINE, [0, 1]) 808 809 def testSO_RCVBUF(self): 810 self.test_udp = 1 811 self.test_tcp_client = 1 812 self.test_tcp_server = 1 813 self._testOption(socket.SOL_SOCKET, socket.SO_RCVBUF, [1024, 4096, 16384]) 814 815 def testSO_REUSEADDR(self): 816 self.test_udp = 1 817 self.test_tcp_client = 1 818 self.test_tcp_server = 1 819 self._testOption(socket.SOL_SOCKET, socket.SO_REUSEADDR, [0, 1]) 820 821 def testSO_SNDBUF(self): 822 self.test_udp = 1 823 self.test_tcp_client = 1 824 self._testOption(socket.SOL_SOCKET, socket.SO_SNDBUF, [1024, 4096, 16384]) 825 826 def testSO_TIMEOUT(self): 827 self.test_udp = 1 828 self.test_tcp_client = 1 829 self.test_tcp_server = 1 830 self._testOption(socket.SOL_SOCKET, socket.SO_TIMEOUT, [0, 1, 1000]) 831 832 def testTCP_NODELAY(self): 833 self.test_tcp_client = 1 834 self._testOption(socket.IPPROTO_TCP, socket.TCP_NODELAY, [0, 1]) 835 836class TestUnsupportedOptions(TestSocketOptions): 837 838 def testSO_ACCEPTCONN(self): 839 self.failUnless(hasattr(socket, 'SO_ACCEPTCONN')) 840 841 def testSO_DEBUG(self): 842 self.failUnless(hasattr(socket, 'SO_DEBUG')) 843 844 def testSO_DONTROUTE(self): 845 self.failUnless(hasattr(socket, 'SO_DONTROUTE')) 846 847 def testSO_ERROR(self): 848 self.failUnless(hasattr(socket, 'SO_ERROR')) 849 850 def testSO_EXCLUSIVEADDRUSE(self): 851 # this is an MS specific option that will not be appearing on java 852 # http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6421091 853 # http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6402335 854 self.failUnless(hasattr(socket, 'SO_EXCLUSIVEADDRUSE')) 855 856 def testSO_RCVLOWAT(self): 857 self.failUnless(hasattr(socket, 'SO_RCVLOWAT')) 858 859 def testSO_RCVTIMEO(self): 860 self.failUnless(hasattr(socket, 'SO_RCVTIMEO')) 861 862 def testSO_REUSEPORT(self): 863 # not yet supported on java 864 # http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6432031 865 self.failUnless(hasattr(socket, 'SO_REUSEPORT')) 866 867 def testSO_SNDLOWAT(self): 868 self.failUnless(hasattr(socket, 'SO_SNDLOWAT')) 869 870 def testSO_SNDTIMEO(self): 871 self.failUnless(hasattr(socket, 'SO_SNDTIMEO')) 872 873 def testSO_TYPE(self): 874 self.failUnless(hasattr(socket, 'SO_TYPE')) 875 876 def testSO_USELOOPBACK(self): 877 self.failUnless(hasattr(socket, 'SO_USELOOPBACK')) 878 879class BasicTCPTest(SocketConnectedTest): 880 881 def __init__(self, methodName='runTest'): 882 SocketConnectedTest.__init__(self, methodName=methodName) 883 884 def testRecv(self): 885 # Testing large receive over TCP 886 msg = self.cli_conn.recv(1024) 887 self.assertEqual(msg, MSG) 888 889 def _testRecv(self): 890 self.serv_conn.send(MSG) 891 892 def testRecvTimeoutMode(self): 893 # Do this test in timeout mode, because the code path is different 894 self.cli_conn.settimeout(10) 895 msg = self.cli_conn.recv(1024) 896 self.assertEqual(msg, MSG) 897 898 def _testRecvTimeoutMode(self): 899 self.serv_conn.settimeout(10) 900 self.serv_conn.send(MSG) 901 902 def testOverFlowRecv(self): 903 # Testing receive in chunks over TCP 904 seg1 = self.cli_conn.recv(len(MSG) - 3) 905 seg2 = self.cli_conn.recv(1024) 906 msg = seg1 + seg2 907 self.assertEqual(msg, MSG) 908 909 def _testOverFlowRecv(self): 910 self.serv_conn.send(MSG) 911 912 def testRecvFrom(self): 913 # Testing large recvfrom() over TCP 914 msg, addr = self.cli_conn.recvfrom(1024) 915 self.assertEqual(msg, MSG) 916 917 def _testRecvFrom(self): 918 self.serv_conn.send(MSG) 919 920 def testOverFlowRecvFrom(self): 921 # Testing recvfrom() in chunks over TCP 922 seg1, addr = self.cli_conn.recvfrom(len(MSG)-3) 923 seg2, addr = self.cli_conn.recvfrom(1024) 924 msg = seg1 + seg2 925 self.assertEqual(msg, MSG) 926 927 def _testOverFlowRecvFrom(self): 928 self.serv_conn.send(MSG) 929 930 def testSendAll(self): 931 # Testing sendall() with a 2048 byte string over TCP 932 msg = '' 933 while 1: 934 read = self.cli_conn.recv(1024) 935 if not read: 936 break 937 msg += read 938 self.assertEqual(msg, 'f' * 2048) 939 940 def _testSendAll(self): 941 big_chunk = 'f' * 2048 942 self.serv_conn.sendall(big_chunk) 943 944 def testFromFd(self): 945 # Testing fromfd() 946 if not hasattr(socket, "fromfd"): 947 return # On Windows, this doesn't exist 948 fd = self.cli_conn.fileno() 949 sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM) 950 msg = sock.recv(1024) 951 self.assertEqual(msg, MSG) 952 953 def _testFromFd(self): 954 self.serv_conn.send(MSG) 955 956 def testShutdown(self): 957 # Testing shutdown() 958 msg = self.cli_conn.recv(1024) 959 self.assertEqual(msg, MSG) 960 961 def _testShutdown(self): 962 self.serv_conn.send(MSG) 963 self.serv_conn.shutdown(2) 964 965 def testSendAfterRemoteClose(self): 966 self.cli_conn.close() 967 968 def _testSendAfterRemoteClose(self): 969 for x in range(5): 970 try: 971 self.serv_conn.send("spam") 972 except socket.error, se: 973 self.failUnlessEqual(se[0], errno.ECONNRESET) 974 return 975 except Exception, x: 976 self.fail("Sending on remotely closed socket raised wrong exception: %s" % x) 977 time.sleep(0.5) 978 self.fail("Sending on remotely closed socket should have raised exception") 979 980 def testDup(self): 981 msg = self.cli_conn.recv(len(MSG)) 982 self.assertEqual(msg, MSG) 983 984 dup_conn = self.cli_conn.dup() 985 msg = dup_conn.recv(len('and ' + MSG)) 986 self.assertEqual(msg, 'and ' + MSG) 987 988 def _testDup(self): 989 self.serv_conn.send(MSG) 990 self.serv_conn.send('and ' + MSG) 991 992class UDPBindTest(unittest.TestCase): 993 994 HOST = HOST 995 PORT = PORT 996 997 def setUp(self): 998 self.sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) 999 1000 def testBindSpecific(self): 1001 self.sock.bind( (self.HOST, self.PORT) ) # Use a specific port 1002 actual_port = self.sock.getsockname()[1] 1003 self.failUnless(actual_port == self.PORT, 1004 "Binding to specific port number should have returned same number: %d != %d" % (actual_port, self.PORT)) 1005 1006 def testBindEphemeral(self): 1007 self.sock.bind( (self.HOST, 0) ) # let system choose a free port 1008 self.failUnless(self.sock.getsockname()[1] != 0, "Binding to port zero should have allocated an ephemeral port number") 1009 1010 def testShutdown(self): 1011 self.sock.bind( (self.HOST, self.PORT) ) 1012 self.sock.shutdown(socket.SHUT_RDWR) 1013 1014 def tearDown(self): 1015 self.sock.close() 1016 1017class BasicUDPTest(ThreadedUDPSocketTest): 1018 1019 def __init__(self, methodName='runTest'): 1020 ThreadedUDPSocketTest.__init__(self, methodName=methodName) 1021 1022 def testSendtoAndRecv(self): 1023 # Testing sendto() and recv() over UDP 1024 msg = self.serv.recv(len(MSG)) 1025 self.assertEqual(msg, MSG) 1026 1027 def _testSendtoAndRecv(self): 1028 self.cli.sendto(MSG, 0, (self.HOST, self.PORT)) 1029 1030 def testSendtoAndRecvTimeoutMode(self): 1031 # Need to test again in timeout mode, which follows 1032 # a different code path 1033 self.serv.settimeout(10) 1034 msg = self.serv.recv(len(MSG)) 1035 self.assertEqual(msg, MSG) 1036 1037 def _testSendtoAndRecvTimeoutMode(self): 1038 self.cli.settimeout(10) 1039 self.cli.sendto(MSG, 0, (self.HOST, self.PORT)) 1040 1041 def testSendAndRecv(self): 1042 # Testing send() and recv() over connect'ed UDP 1043 msg = self.serv.recv(len(MSG)) 1044 self.assertEqual(msg, MSG) 1045 1046 def _testSendAndRecv(self): 1047 self.cli.connect( (self.HOST, self.PORT) ) 1048 self.cli.send(MSG, 0) 1049 1050 def testSendAndRecvTimeoutMode(self): 1051 # Need to test again in timeout mode, which follows 1052 # a different code path 1053 self.serv.settimeout(10) 1054 # Testing send() and recv() over connect'ed UDP 1055 msg = self.serv.recv(len(MSG)) 1056 self.assertEqual(msg, MSG) 1057 1058 def _testSendAndRecvTimeoutMode(self): 1059 self.cli.connect( (self.HOST, self.PORT) ) 1060 self.cli.settimeout(10) 1061 self.cli.send(MSG, 0) 1062 1063 def testRecvFrom(self): 1064 # Testing recvfrom() over UDP 1065 msg, addr = self.serv.recvfrom(len(MSG)) 1066 self.assertEqual(msg, MSG) 1067 1068 def _testRecvFrom(self): 1069 self.cli.sendto(MSG, 0, (self.HOST, self.PORT)) 1070 1071 def testRecvFromTimeoutMode(self): 1072 # Need to test again in timeout mode, which follows 1073 # a different code path 1074 self.serv.settimeout(10) 1075 msg, addr = self.serv.recvfrom(len(MSG)) 1076 self.assertEqual(msg, MSG) 1077 1078 def _testRecvFromTimeoutMode(self): 1079 self.cli.settimeout(10) 1080 self.cli.sendto(MSG, 0, (self.HOST, self.PORT)) 1081 1082 def testSendtoEightBitSafe(self): 1083 # This test is necessary because java only supports signed bytes 1084 msg = self.serv.recv(len(EIGHT_BIT_MSG)) 1085 self.assertEqual(msg, EIGHT_BIT_MSG) 1086 1087 def _testSendtoEightBitSafe(self): 1088 self.cli.sendto(EIGHT_BIT_MSG, 0, (self.HOST, self.PORT)) 1089 1090 def testSendtoEightBitSafeTimeoutMode(self): 1091 # Need to test again in timeout mode, which follows 1092 # a different code path 1093 self.serv.settimeout(10) 1094 msg = self.serv.recv(len(EIGHT_BIT_MSG)) 1095 self.assertEqual(msg, EIGHT_BIT_MSG) 1096 1097 def _testSendtoEightBitSafeTimeoutMode(self): 1098 self.cli.settimeout(10) 1099 self.cli.sendto(EIGHT_BIT_MSG, 0, (self.HOST, self.PORT)) 1100 1101class UDPBroadcastTest(ThreadedUDPSocketTest): 1102 1103 def setUp(self): 1104 self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 1105 self.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 1106 1107 def testBroadcast(self): 1108 self.serv.bind( ("", self.PORT) ) 1109 msg = self.serv.recv(len(EIGHT_BIT_MSG)) 1110 self.assertEqual(msg, EIGHT_BIT_MSG) 1111 1112 def _testBroadcast(self): 1113 self.cli.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) 1114 self.cli.sendto(EIGHT_BIT_MSG, ("<broadcast>", self.PORT) ) 1115 1116class BasicSocketPairTest(SocketPairTest): 1117 1118 def __init__(self, methodName='runTest'): 1119 SocketPairTest.__init__(self, methodName=methodName) 1120 1121 def testRecv(self): 1122 msg = self.serv.recv(1024) 1123 self.assertEqual(msg, MSG) 1124 1125 def _testRecv(self): 1126 self.cli.send(MSG) 1127 1128 def testSend(self): 1129 self.serv.send(MSG) 1130 1131 def _testSend(self): 1132 msg = self.cli.recv(1024) 1133 self.assertEqual(msg, MSG) 1134 1135class NonBlockingTCPServerTests(SocketTCPTest): 1136 1137 def testSetBlocking(self): 1138 # Testing whether set blocking works 1139 self.serv.setblocking(0) 1140 start = time.time() 1141 try: 1142 self.serv.accept() 1143 except socket.error: 1144 pass 1145 end = time.time() 1146 self.assert_((end - start) < 1.0, "Error setting non-blocking mode.") 1147 1148 def testGetBlocking(self): 1149 # Testing whether set blocking works 1150 self.serv.setblocking(0) 1151 self.failUnless(not self.serv.getblocking(), "Getblocking return true instead of false") 1152 self.serv.setblocking(1) 1153 self.failUnless(self.serv.getblocking(), "Getblocking return false instead of true") 1154 1155 def testAcceptNoConnection(self): 1156 # Testing non-blocking accept returns immediately when no connection 1157 self.serv.setblocking(0) 1158 try: 1159 conn, addr = self.serv.accept() 1160 except socket.error: 1161 pass 1162 else: 1163 self.fail("Error trying to do non-blocking accept.") 1164 1165class NonBlockingTCPTests(ThreadedTCPSocketTest): 1166 1167 def __init__(self, methodName='runTest'): 1168 ThreadedTCPSocketTest.__init__(self, methodName=methodName) 1169 1170 def testAcceptConnection(self): 1171 # Testing non-blocking accept works when connection present 1172 self.serv.setblocking(0) 1173 read, write, err = select.select([self.serv], [], []) 1174 if self.serv in read: 1175 conn, addr = self.serv.accept() 1176 else: 1177 self.fail("Error trying to do accept after select: server socket was not in 'read'able list") 1178 1179 def _testAcceptConnection(self): 1180 # Make a connection to the server 1181 self.cli.connect((self.HOST, self.PORT)) 1182 1183 # 1184 # AMAK: 20070311 1185 # Introduced a new test for non-blocking connect 1186 # Renamed old testConnect to testBlockingConnect 1187 # 1188 1189 def testBlockingConnect(self): 1190 # Testing blocking connect 1191 conn, addr = self.serv.accept() 1192 1193 def _testBlockingConnect(self): 1194 # Testing blocking connect 1195 self.cli.settimeout(10) 1196 self.cli.connect((self.HOST, self.PORT)) 1197 1198 def testNonBlockingConnect(self): 1199 # Testing non-blocking connect 1200 conn, addr = self.serv.accept() 1201 1202 def _testNonBlockingConnect(self): 1203 # Testing non-blocking connect 1204 self.cli.setblocking(0) 1205 result = self.cli.connect_ex((self.HOST, self.PORT)) 1206 rfds, wfds, xfds = select.select([], [self.cli], []) 1207 self.failUnless(self.cli in wfds) 1208 try: 1209 self.cli.send(MSG) 1210 except socket.error: 1211 self.fail("Sending on connected socket should not have raised socket.error") 1212 1213 # 1214 # AMAK: 20070518 1215 # Introduced a new test for connect with bind to specific local address 1216 # 1217 1218 def testConnectWithLocalBind(self): 1219 # Test blocking connect 1220 conn, addr = self.serv.accept() 1221 1222 def _testConnectWithLocalBind(self): 1223 # Testing blocking connect with local bind 1224 cli_port = self.PORT - 1 1225 while True: 1226 # Keep trying until a local port is available 1227 self.cli.settimeout(1) 1228 self.cli.bind( (self.HOST, cli_port) ) 1229 try: 1230 self.cli.connect((self.HOST, self.PORT)) 1231 break 1232 except socket.error, se: 1233 # cli_port is in use (maybe in TIME_WAIT state from a 1234 # previous test run). reset the client socket and try 1235 # again 1236 self.failUnlessEqual(se[0], errno.EADDRINUSE) 1237 try: 1238 self.cli.close() 1239 except socket.error: 1240 pass 1241 self.clientSetUp() 1242 cli_port -= 1 1243 bound_host, bound_port = self.cli.getsockname() 1244 self.failUnlessEqual(bound_port, cli_port) 1245 1246 def testRecvData(self): 1247 # Testing non-blocking recv 1248 conn, addr = self.serv.accept() 1249 conn.setblocking(0) 1250 rfds, wfds, xfds = select.select([conn], [], []) 1251 if conn in rfds: 1252 msg = conn.recv(len(MSG)) 1253 self.assertEqual(msg, MSG) 1254 else: 1255 self.fail("Non-blocking socket with data should been in read list.") 1256 1257 def _testRecvData(self): 1258 self.cli.connect((self.HOST, self.PORT)) 1259 self.cli.send(MSG) 1260 1261 def testRecvNoData(self): 1262 # Testing non-blocking recv 1263 conn, addr = self.serv.accept() 1264 conn.setblocking(0) 1265 try: 1266 msg = conn.recv(len(MSG)) 1267 except socket.error: 1268 pass 1269 else: 1270 self.fail("Non-blocking recv of no data should have raised socket.error.") 1271 1272 def _testRecvNoData(self): 1273 self.cli.connect((self.HOST, self.PORT)) 1274 time.sleep(0.1) 1275 1276class NonBlockingUDPTests(ThreadedUDPSocketTest): pass 1277 1278# 1279# TODO: Write some non-blocking UDP tests 1280# 1281 1282class TCPFileObjectClassOpenCloseTests(SocketConnectedTest): 1283 1284 def testCloseFileDoesNotCloseSocket(self): 1285 # This test is necessary on java/jython 1286 msg = self.cli_conn.recv(1024) 1287 self.assertEqual(msg, MSG) 1288 1289 def _testCloseFileDoesNotCloseSocket(self): 1290 self.cli_file = self.serv_conn.makefile('wb') 1291 self.cli_file.close() 1292 try: 1293 self.serv_conn.send(MSG) 1294 except Exception, x: 1295 self.fail("Closing file wrapper appears to have closed underlying socket: %s" % str(x)) 1296 1297 def testCloseSocketDoesNotCloseFile(self): 1298 msg = self.cli_conn.recv(1024) 1299 self.assertEqual(msg, MSG) 1300 1301 def _testCloseSocketDoesNotCloseFile(self): 1302 self.cli_file = self.serv_conn.makefile('wb') 1303 self.serv_conn.close() 1304 try: 1305 self.cli_file.write(MSG) 1306 self.cli_file.flush() 1307 except Exception, x: 1308 self.fail("Closing socket appears to have closed file wrapper: %s" % str(x)) 1309 1310class UDPFileObjectClassOpenCloseTests(ThreadedUDPSocketTest): 1311 1312 def testCloseFileDoesNotCloseSocket(self): 1313 # This test is necessary on java/jython 1314 msg = self.serv.recv(1024) 1315 self.assertEqual(msg, MSG) 1316 1317 def _testCloseFileDoesNotCloseSocket(self): 1318 self.cli_file = self.cli.makefile('wb') 1319 self.cli_file.close() 1320 try: 1321 self.cli.sendto(MSG, 0, (self.HOST, self.PORT)) 1322 except Exception, x: 1323 self.fail("Closing file wrapper appears to have closed underlying socket: %s" % str(x)) 1324 1325 def testCloseSocketDoesNotCloseFile(self): 1326 self.serv_file = self.serv.makefile('rb') 1327 self.serv.close() 1328 msg = self.serv_file.readline() 1329 self.assertEqual(msg, MSG) 1330 1331 def _testCloseSocketDoesNotCloseFile(self): 1332 try: 1333 self.cli.sendto(MSG, 0, (self.HOST, self.PORT)) 1334 except Exception, x: 1335 self.fail("Closing file wrapper appears to have closed underlying socket: %s" % str(x)) 1336 1337class FileAndDupOpenCloseTests(SocketConnectedTest): 1338 1339 def testCloseDoesNotCloseOthers(self): 1340 msg = self.cli_conn.recv(len(MSG)) 1341 self.assertEqual(msg, MSG) 1342 1343 msg = self.cli_conn.recv(len('and ' + MSG)) 1344 self.assertEqual(msg, 'and ' + MSG) 1345 1346 def _testCloseDoesNotCloseOthers(self): 1347 self.dup_conn1 = self.serv_conn.dup() 1348 self.dup_conn2 = self.serv_conn.dup() 1349 self.cli_file = self.serv_conn.makefile('wb') 1350 self.serv_conn.close() 1351 self.dup_conn1.close() 1352 1353 try: 1354 self.serv_conn.send(MSG) 1355 except socket.error, se: 1356 self.failUnlessEqual(se[0], errno.EBADF) 1357 else: 1358 self.fail("Original socket did not close") 1359 try: 1360 self.dup_conn1.send(MSG) 1361 except socket.error, se: 1362 self.failUnlessEqual(se[0], errno.EBADF) 1363 else: 1364 self.fail("Duplicate socket 1 did not close") 1365 1366 self.dup_conn2.send(MSG) 1367 self.dup_conn2.close() 1368 1369 try: 1370 self.cli_file.write('and ' + MSG) 1371 except Exception, x: 1372 self.fail("Closing others appears to have closed the socket file: %s" % str(x)) 1373 self.cli_file.close() 1374 1375class FileObjectClassTestCase(SocketConnectedTest): 1376 1377 bufsize = -1 # Use default buffer size 1378 1379 def __init__(self, methodName='runTest'): 1380 SocketConnectedTest.__init__(self, methodName=methodName) 1381 1382 def setUp(self): 1383 SocketConnectedTest.setUp(self) 1384 self.serv_file = self.cli_conn.makefile('rb', self.bufsize) 1385 1386 def tearDown(self): 1387 self.serv_file.close() 1388 self.assert_(self.serv_file.closed) 1389 self.serv_file = None 1390 SocketConnecte…
Large files files are truncated, but you can click here to view the full file