/Lib/test/test_socket.py
Python | 2508 lines | 2249 code | 155 blank | 104 comment | 137 complexity | 8b43af09cc79562df502e66d3bd8843e 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, expected_name_starts in [ 281 ('IPPROTO_ICMP', ['IPPROTO_']), 282 ('IPPROTO_TCP', ['IPPROTO_']), 283 ('IPPROTO_UDP', ['IPPROTO_']), 284 ('SO_BROADCAST', ['SO_', 'TCP_']), 285 ('SO_KEEPALIVE', ['SO_', 'TCP_']), 286 ('SO_ACCEPTCONN', ['SO_', 'TCP_']), 287 ('SO_DEBUG', ['SO_', 'TCP_']), 288 ('SOCK_DGRAM', ['SOCK_']), 289 ('SOCK_RAW', ['SOCK_']), 290 ('SOL_SOCKET', ['SOL_', 'IPPROTO_']), 291 ('TCP_NODELAY', ['SO_', 'TCP_']), 292 ]: 293 self.failUnlessEqual(socket._constant_to_name(getattr(socket, name), expected_name_starts), name) 294 295 def testHostnameRes(self): 296 # Testing hostname resolution mechanisms 297 hostname = socket.gethostname() 298 self.assert_(isinstance(hostname, str)) 299 try: 300 ip = socket.gethostbyname(hostname) 301 self.assert_(isinstance(ip, str)) 302 except socket.error: 303 # Probably name lookup wasn't set up right; skip this test 304 self.fail("Probably name lookup wasn't set up right; skip testHostnameRes.gethostbyname") 305 return 306 self.assert_(ip.find('.') >= 0, "Error resolving host to ip.") 307 try: 308 hname, aliases, ipaddrs = socket.gethostbyaddr(ip) 309 self.assert_(isinstance(hname, str)) 310 for hosts in aliases, ipaddrs: 311 self.assert_(all(isinstance(host, str) for host in hosts)) 312 except socket.error: 313 # Probably a similar problem as above; skip this test 314 self.fail("Probably name lookup wasn't set up right; skip testHostnameRes.gethostbyaddr") 315 return 316 all_host_names = [hostname, hname] + aliases 317 fqhn = socket.getfqdn() 318 self.assert_(isinstance(fqhn, str)) 319 if not fqhn in all_host_names: 320 self.fail("Error testing host resolution mechanisms.") 321 322 def testRefCountGetNameInfo(self): 323 # Testing reference count for getnameinfo 324 import sys 325 if hasattr(sys, "getrefcount"): 326 try: 327 # On some versions, this loses a reference 328 orig = sys.getrefcount(__name__) 329 socket.getnameinfo(__name__,0) 330 except SystemError: 331 if sys.getrefcount(__name__) <> orig: 332 self.fail("socket.getnameinfo loses a reference") 333 334 def testInterpreterCrash(self): 335 if sys.platform[:4] == 'java': return 336 # Making sure getnameinfo doesn't crash the interpreter 337 try: 338 # On some versions, this crashes the interpreter. 339 socket.getnameinfo(('x', 0, 0, 0), 0) 340 except socket.error: 341 pass 342 343# Need to implement binary AND for ints and longs 344 345 def testNtoH(self): 346 if sys.platform[:4] == 'java': return # problems with int & long 347 # This just checks that htons etc. are their own inverse, 348 # when looking at the lower 16 or 32 bits. 349 sizes = {socket.htonl: 32, socket.ntohl: 32, 350 socket.htons: 16, socket.ntohs: 16} 351 for func, size in sizes.items(): 352 mask = (1L<<size) - 1 353 for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210): 354 self.assertEqual(i & mask, func(func(i&mask)) & mask) 355 356 swapped = func(mask) 357 self.assertEqual(swapped & mask, mask) 358 self.assertRaises(OverflowError, func, 1L<<34) 359 360 def testGetServBy(self): 361 eq = self.assertEqual 362 # Find one service that exists, then check all the related interfaces. 363 # I've ordered this by protocols that have both a tcp and udp 364 # protocol, at least for modern Linuxes. 365 if sys.platform in ('linux2', 'freebsd4', 'freebsd5', 'freebsd6', 366 'darwin') or is_bsd: 367 # avoid the 'echo' service on this platform, as there is an 368 # assumption breaking non-standard port/protocol entry 369 services = ('daytime', 'qotd', 'domain') 370 else: 371 services = ('echo', 'daytime', 'domain') 372 for service in services: 373 try: 374 port = socket.getservbyname(service, 'tcp') 375 break 376 except socket.error: 377 pass 378 else: 379 raise socket.error 380 # Try same call with optional protocol omitted 381 port2 = socket.getservbyname(service) 382 eq(port, port2) 383 # Try udp, but don't barf it it doesn't exist 384 try: 385 udpport = socket.getservbyname(service, 'udp') 386 except socket.error: 387 udpport = None 388 else: 389 eq(udpport, port) 390 # Now make sure the lookup by port returns the same service name 391 eq(socket.getservbyport(port2), service) 392 eq(socket.getservbyport(port, 'tcp'), service) 393 if udpport is not None: 394 eq(socket.getservbyport(udpport, 'udp'), service) 395 396 def testGetServByExceptions(self): 397 # First getservbyname 398 try: 399 result = socket.getservbyname("nosuchservice") 400 except socket.error: 401 pass 402 except Exception, x: 403 self.fail("getservbyname raised wrong exception for non-existent service: %s" % str(x)) 404 else: 405 self.fail("getservbyname failed to raise exception for non-existent service: %s" % str(result)) 406 407 # Now getservbyport 408 try: 409 result = socket.getservbyport(55555) 410 except socket.error: 411 pass 412 except Exception, x: 413 self.fail("getservbyport raised wrong exception for unknown port: %s" % str(x)) 414 else: 415 self.fail("getservbyport failed to raise exception for unknown port: %s" % str(result)) 416 417 def testGetProtoByName(self): 418 self.failUnlessEqual(socket.IPPROTO_TCP, socket.getprotobyname("tcp")) 419 self.failUnlessEqual(socket.IPPROTO_UDP, socket.getprotobyname("udp")) 420 try: 421 result = socket.getprotobyname("nosuchproto") 422 except socket.error: 423 pass 424 except Exception, x: 425 self.fail("getprotobyname raised wrong exception for unknown protocol: %s" % str(x)) 426 else: 427 self.fail("getprotobyname failed to raise exception for unknown protocol: %s" % str(result)) 428 429 def testDefaultTimeout(self): 430 # Testing default timeout 431 # The default timeout should initially be None 432 self.assertEqual(socket.getdefaulttimeout(), None) 433 s = socket.socket() 434 self.assertEqual(s.gettimeout(), None) 435 s.close() 436 437 # Set the default timeout to 10, and see if it propagates 438 socket.setdefaulttimeout(10) 439 self.assertEqual(socket.getdefaulttimeout(), 10) 440 s = socket.socket() 441 self.assertEqual(s.gettimeout(), 10) 442 s.close() 443 444 # Reset the default timeout to None, and see if it propagates 445 socket.setdefaulttimeout(None) 446 self.assertEqual(socket.getdefaulttimeout(), None) 447 s = socket.socket() 448 self.assertEqual(s.gettimeout(), None) 449 s.close() 450 451 # Check that setting it to an invalid value raises ValueError 452 self.assertRaises(ValueError, socket.setdefaulttimeout, -1) 453 454 # Check that setting it to an invalid type raises TypeError 455 self.assertRaises(TypeError, socket.setdefaulttimeout, "spam") 456 457 def testIPv4toString(self): 458 if not hasattr(socket, 'inet_pton'): 459 return # No inet_pton() on this platform 460 from socket import inet_aton as f, inet_pton, AF_INET 461 g = lambda a: inet_pton(AF_INET, a) 462 463 self.assertEquals('\x00\x00\x00\x00', f('0.0.0.0')) 464 self.assertEquals('\xff\x00\xff\x00', f('255.0.255.0')) 465 self.assertEquals('\xaa\xaa\xaa\xaa', f('170.170.170.170')) 466 self.assertEquals('\x01\x02\x03\x04', f('1.2.3.4')) 467 468 self.assertEquals('\x00\x00\x00\x00', g('0.0.0.0')) 469 self.assertEquals('\xff\x00\xff\x00', g('255.0.255.0')) 470 self.assertEquals('\xaa\xaa\xaa\xaa', g('170.170.170.170')) 471 472 def testIPv6toString(self): 473 if not hasattr(socket, 'inet_pton'): 474 return # No inet_pton() on this platform 475 try: 476 from socket import inet_pton, AF_INET6, has_ipv6 477 if not has_ipv6: 478 return 479 except ImportError: 480 return 481 f = lambda a: inet_pton(AF_INET6, a) 482 483 self.assertEquals('\x00' * 16, f('::')) 484 self.assertEquals('\x00' * 16, f('0::0')) 485 self.assertEquals('\x00\x01' + '\x00' * 14, f('1::')) 486 self.assertEquals( 487 '\x45\xef\x76\xcb\x00\x1a\x56\xef\xaf\xeb\x0b\xac\x19\x24\xae\xae', 488 f('45ef:76cb:1a:56ef:afeb:bac:1924:aeae') 489 ) 490 491 def test_inet_pton_exceptions(self): 492 if not hasattr(socket, 'inet_pton'): 493 return # No inet_pton() on this platform 494 495 try: 496 socket.inet_pton(socket.AF_UNSPEC, "doesntmatter") 497 except socket.error, se: 498 self.failUnlessEqual(se[0], errno.EAFNOSUPPORT) 499 except Exception, x: 500 self.fail("inet_pton raised wrong exception for incorrect address family AF_UNSPEC: %s" % str(x)) 501 502 try: 503 socket.inet_pton(socket.AF_INET, "1.2.3.") 504 except socket.error, se: 505 pass 506 except Exception, x: 507 self.fail("inet_pton raised wrong exception for invalid AF_INET address: %s" % str(x)) 508 509 try: 510 socket.inet_pton(socket.AF_INET6, ":::") 511 except socket.error, se: 512 pass 513 except Exception, x: 514 self.fail("inet_pton raised wrong exception for invalid AF_INET6 address: %s" % str(x)) 515 516 def testStringToIPv4(self): 517 if not hasattr(socket, 'inet_ntop'): 518 return # No inet_ntop() on this platform 519 from socket import inet_ntoa as f, inet_ntop, AF_INET 520 g = lambda a: inet_ntop(AF_INET, a) 521 522 self.assertEquals('1.0.1.0', f('\x01\x00\x01\x00')) 523 self.assertEquals('170.85.170.85', f('\xaa\x55\xaa\x55')) 524 self.assertEquals('255.255.255.255', f('\xff\xff\xff\xff')) 525 self.assertEquals('1.2.3.4', f('\x01\x02\x03\x04')) 526 527 self.assertEquals('1.0.1.0', g('\x01\x00\x01\x00')) 528 self.assertEquals('170.85.170.85', g('\xaa\x55\xaa\x55')) 529 self.assertEquals('255.255.255.255', g('\xff\xff\xff\xff')) 530 531 def testStringToIPv6(self): 532 if not hasattr(socket, 'inet_ntop'): 533 return # No inet_ntop() on this platform 534 try: 535 from socket import inet_ntop, AF_INET6, has_ipv6 536 if not has_ipv6: 537 return 538 except ImportError: 539 return 540 f = lambda a: inet_ntop(AF_INET6, a) 541 542# self.assertEquals('::', f('\x00' * 16)) 543# self.assertEquals('::1', f('\x00' * 15 + '\x01')) 544 # java.net.InetAddress always return the full unabbreviated form 545 self.assertEquals('0:0:0:0:0:0:0:0', f('\x00' * 16)) 546 self.assertEquals('0:0:0:0:0:0:0:1', f('\x00' * 15 + '\x01')) 547 self.assertEquals( 548 'aef:b01:506:1001:ffff:9997:55:170', 549 f('\x0a\xef\x0b\x01\x05\x06\x10\x01\xff\xff\x99\x97\x00\x55\x01\x70') 550 ) 551 552 def test_inet_ntop_exceptions(self): 553 if not hasattr(socket, 'inet_ntop'): 554 return # No inet_ntop() on this platform 555 valid_address = '\x01\x01\x01\x01' 556 invalid_address = '\x01\x01\x01\x01\x01' 557 558 try: 559 socket.inet_ntop(socket.AF_UNSPEC, valid_address) 560 except ValueError, v: 561 pass 562 except Exception, x: 563 self.fail("inet_ntop raised wrong exception for incorrect address family AF_UNSPEC: %s" % str(x)) 564 565 try: 566 socket.inet_ntop(socket.AF_INET, invalid_address) 567 except ValueError, v: 568 pass 569 except Exception, x: 570 self.fail("inet_ntop raised wrong exception for invalid AF_INET address: %s" % str(x)) 571 572 try: 573 socket.inet_ntop(socket.AF_INET6, invalid_address) 574 except ValueError, v: 575 pass 576 except Exception, x: 577 self.fail("inet_ntop raised wrong exception for invalid AF_INET address: %s" % str(x)) 578 579 # XXX The following don't test module-level functionality... 580 581 def testSockName(self): 582 # Testing getsockname() 583 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 584 sock.bind(("0.0.0.0", PORT+1)) 585 name = sock.getsockname() 586 self.assertEqual(name, ("0.0.0.0", PORT+1)) 587 588 def testSockAttributes(self): 589 # Testing required attributes 590 for family in [socket.AF_INET, socket.AF_INET6]: 591 for sock_type in [socket.SOCK_STREAM, socket.SOCK_DGRAM]: 592 s = socket.socket(family, sock_type) 593 self.assertEqual(s.family, family) 594 self.assertEqual(s.type, sock_type) 595 if sock_type == socket.SOCK_STREAM: 596 self.assertEqual(s.proto, socket.IPPROTO_TCP) 597 else: 598 self.assertEqual(s.proto, socket.IPPROTO_UDP) 599 600 def testGetSockOpt(self): 601 # Testing getsockopt() 602 # We know a socket should start without reuse==0 603 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 604 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) 605 self.failIf(reuse != 0, "initial mode is reuse") 606 607 def testSetSockOpt(self): 608 # Testing setsockopt() 609 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 610 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 611 reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) 612 self.failIf(reuse == 0, "failed to set reuse mode") 613 614 def testSendAfterClose(self): 615 # testing send() after close() with timeout 616 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 617 sock.settimeout(1) 618 sock.close() 619 self.assertRaises(socket.error, sock.send, "spam") 620 621class IPAddressTests(unittest.TestCase): 622 623 def testValidIpV4Addresses(self): 624 for a in [ 625 "0.0.0.1", 626 "1.0.0.1", 627 "127.0.0.1", 628 "255.12.34.56", 629 "255.255.255.255", 630 ]: 631 self.failUnless(socket.is_ipv4_address(a), "is_ipv4_address failed for valid IPV4 address '%s'" % a) 632 self.failUnless(socket.is_ip_address(a), "is_ip_address failed for valid IPV4 address '%s'" % a) 633 634 def testInvalidIpV4Addresses(self): 635 for a in [ 636 "99.2", 637 "99.2.4", 638 "-10.1.2.3", 639 "256.0.0.0", 640 "0.256.0.0", 641 "0.0.256.0", 642 "0.0.0.256", 643 "255.24.x.100", 644 "255.24.-1.128", 645 "255.24.-1.128.", 646 "255.0.0.999", 647 ]: 648 self.failUnless(not socket.is_ipv4_address(a), "not is_ipv4_address failed for invalid IPV4 address '%s'" % a) 649 self.failUnless(not socket.is_ip_address(a), "not is_ip_address failed for invalid IPV4 address '%s'" % a) 650 651 def testValidIpV6Addresses(self): 652 for a in [ 653 "::", 654 "::1", 655 "fe80::1", 656 "::192.168.1.1", 657 "0:0:0:0:0:0:0:0", 658 "1080::8:800:2C:4A", 659 "FEC0:0:0:0:0:0:0:1", 660 "::FFFF:192.168.1.1", 661 "abcd:ef:111:f123::1", 662 "1138:0:0:0:8:80:800:417A", 663 "fecc:face::b00c:f001:fedc:fedd", 664 "CaFe:BaBe:dEAd:BeeF:12:345:6789:abcd", 665 ]: 666 self.failUnless(socket.is_ipv6_address(a), "is_ipv6_address failed for valid IPV6 address '%s'" % a) 667 self.failUnless(socket.is_ip_address(a), "is_ip_address failed for valid IPV6 address '%s'" % a) 668 669 def testInvalidIpV6Addresses(self): 670 for a in [ 671 "2001:db8:::192.0.2.1", # from RFC 5954 672 "CaFe:BaBe:dEAd:BeeF:12:345:6789:abcd:", 673 "CaFe:BaBe:dEAd:BeeF:12:345:6789:abcd:ef", 674 "CaFFe:1a77e:dEAd:BeeF:12:345:6789:abcd", 675 ]: 676 self.failUnless(not socket.is_ipv6_address(a), "not is_ipv6_address failed for invalid IPV6 address '%s'" % a) 677 self.failUnless(not socket.is_ip_address(a), "not is_ip_address failed for invalid IPV6 address '%s'" % a) 678 679 def testRFC5952(self): 680 for a in [ 681 "2001:db8::", 682 "2001:db8::1", 683 "2001:db8:0::1", 684 "2001:db8:0:0::1", 685 "2001:db8:0:0:0::1", 686 "2001:DB8:0:0:1::1", 687 "2001:db8:0:0:1::1", 688 "2001:db8::1:0:0:1", 689 "2001:0db8::1:0:0:1", 690 "2001:db8::0:1:0:0:1", 691 "2001:db8:0:0:1:0:0:1", 692 "2001:db8:0000:0:1::1", 693 "2001:db8::aaaa:0:0:1", 694 "2001:db8:0:0:aaaa::1", 695 "2001:0db8:0:0:1:0:0:1", 696 "2001:db8:aaaa:bbbb:cccc:dddd::1", 697 "2001:db8:aaaa:bbbb:cccc:dddd:0:1", 698 "2001:db8:aaaa:bbbb:cccc:dddd:eeee:1", 699 "2001:db8:aaaa:bbbb:cccc:dddd:eeee:01", 700 "2001:db8:aaaa:bbbb:cccc:dddd:eeee:001", 701 "2001:db8:aaaa:bbbb:cccc:dddd:eeee:0001", 702 "2001:db8:aaaa:bbbb:cccc:dddd:eeee:aaaa", 703 "2001:db8:aaaa:bbbb:cccc:dddd:eeee:AAAA", 704 "2001:db8:aaaa:bbbb:cccc:dddd:eeee:AaAa", 705 ]: 706 self.failUnless(socket.is_ipv6_address(a), "is_ipv6_address failed for valid RFC 5952 IPV6 address '%s'" % a) 707 self.failUnless(socket.is_ip_address(a), "is_ip_address failed for valid RFC 5952 IPV6 address '%s'" % a) 708 709class TestSocketOptions(unittest.TestCase): 710 711 def setUp(self): 712 self.test_udp = self.test_tcp_client = self.test_tcp_server = 0 713 714 def _testSetAndGetOption(self, sock, level, option, values): 715 for expected_value in values: 716 sock.setsockopt(level, option, expected_value) 717 retrieved_value = sock.getsockopt(level, option) 718 msg = "Retrieved option(%s, %s) value %s != %s(value set)" % (level, option, retrieved_value, expected_value) 719 if option == socket.SO_RCVBUF: 720 self.assert_(retrieved_value >= expected_value, msg) 721 else: 722 self.failUnlessEqual(retrieved_value, expected_value, msg) 723 724 def _testUDPOption(self, level, option, values): 725 try: 726 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 727 self._testSetAndGetOption(sock, level, option, values) 728 # now bind the socket i.e. cause the implementation socket to be created 729 sock.bind( (HOST, PORT) ) 730 retrieved_option_value = sock.getsockopt(level, option) 731 self.failUnlessEqual(retrieved_option_value, values[-1], \ 732 "Option value '(%s, %s)'='%s' did not propagate to implementation socket: got %s" % (level, option, values[-1], retrieved_option_value) ) 733 self._testSetAndGetOption(sock, level, option, values) 734 finally: 735 sock.close() 736 737 def _testTCPClientOption(self, level, option, values): 738 sock = None 739 try: 740 # First listen on a server socket, so that the connection won't be refused. 741 server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 742 server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 743 server_sock.bind( (HOST, PORT) ) 744 server_sock.listen(50) 745 # Now do the tests 746 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 747 self._testSetAndGetOption(sock, level, option, values) 748 # now connect the socket i.e. cause the implementation socket to be created 749 # First bind, so that the SO_REUSEADDR setting propagates 750 sock.bind( (HOST, PORT+1) ) 751 sock.connect( (HOST, PORT) ) 752 retrieved_option_value = sock.getsockopt(level, option) 753 msg = "Option value '%s'='%s' did not propagate to implementation socket: got %s" % (option, values[-1], retrieved_option_value) 754 if option in (socket.SO_RCVBUF, socket.SO_SNDBUF): 755 # NOTE: there's no guarantee that bufsize will be the 756 # exact setsockopt value, particularly after 757 # establishing a connection. seems it will be *at least* 758 # the values we test (which are rather small) on 759 # BSDs. 760 self.assert_(retrieved_option_value >= values[-1], msg) 761 else: 762 self.failUnlessEqual(retrieved_option_value, values[-1], msg) 763 self._testSetAndGetOption(sock, level, option, values) 764 finally: 765 server_sock.close() 766 if sock: 767 sock.close() 768 769 def _testTCPClientInheritedOption(self, level, option, values): 770 cli_sock = accepted_sock = None 771 try: 772 server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 773 server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 774 self._testSetAndGetOption(server_sock, level, option, values) 775 # now bind and listen on the socket i.e. cause the implementation socket to be created 776 server_sock.bind( (HOST, PORT) ) 777 server_sock.listen(50) 778 # Now create client socket to connect to server 779 cli_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 780 cli_sock.connect( (HOST, PORT) ) 781 accepted_sock = server_sock.accept()[0] 782 retrieved_option_value = accepted_sock.getsockopt(level, option) 783 msg = "Option value '(%s,%s)'='%s' did not propagate to accepted socket: got %s" % (level, option, values[-1], retrieved_option_value) 784 if option == socket.SO_RCVBUF: 785 # NOTE: see similar bsd/solaris workaround above 786 self.assert_(retrieved_option_value >= values[-1], msg) 787 else: 788 self.failUnlessEqual(retrieved_option_value, values[-1], msg) 789 self._testSetAndGetOption(accepted_sock, level, option, values) 790 finally: 791 server_sock.close() 792 if cli_sock: 793 cli_sock.close() 794 if accepted_sock: 795 accepted_sock.close() 796 797 def _testTCPServerOption(self, level, option, values): 798 try: 799 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 800 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 801 self._testSetAndGetOption(sock, level, option, values) 802 # now bind and listen on the socket i.e. cause the implementation socket to be created 803 sock.bind( (HOST, PORT) ) 804 sock.listen(50) 805 retrieved_option_value = sock.getsockopt(level, option) 806 msg = "Option value '(%s,%s)'='%s' did not propagate to implementation socket. Got %s" % (level, option, values[-1], retrieved_option_value) 807 if option == socket.SO_RCVBUF: 808 # NOTE: see similar bsd/solaris workaround above 809 self.assert_(retrieved_option_value >= values[-1], msg) 810 else: 811 self.failUnlessEqual(retrieved_option_value, values[-1], msg) 812 self._testSetAndGetOption(sock, level, option, values) 813 finally: 814 sock.close() 815 816 def _testOption(self, level, option, values): 817 for flag, func in [ 818 (self.test_udp, self._testUDPOption), 819 (self.test_tcp_client, self._testTCPClientOption), 820 (self.test_tcp_server, self._testTCPServerOption), 821 ]: 822 if flag: 823 func(level, option, values) 824 else: 825 try: 826 func(level, option, values) 827 except socket.error, se: 828 self.failUnlessEqual(se[0], errno.ENOPROTOOPT, "Wrong errno from unsupported option exception: %d" % se[0]) 829 except Exception, x: 830 self.fail("Wrong exception raised from unsupported option: %s" % str(x)) 831 else: 832 self.fail("Setting unsupported option should have raised an exception") 833 834 def _testInheritedOption(self, level, option, values): 835 try: 836 self._testTCPClientInheritedOption(level, option, values) 837 except Exception, x: 838 self.fail("Inherited option should not have raised exception: %s" % str(x)) 839 840class TestSupportedOptions(TestSocketOptions): 841 842 def testSO_BROADCAST(self): 843 self.test_udp = 1 844 self._testOption(socket.SOL_SOCKET, socket.SO_BROADCAST, [0, 1]) 845 846 def testSO_KEEPALIVE(self): 847 self.test_tcp_client = 1 848 self.test_tcp_server = 1 849 self._testOption(socket.SOL_SOCKET, socket.SO_KEEPALIVE, [0, 1]) 850 self._testInheritedOption(socket.SOL_SOCKET, socket.SO_KEEPALIVE, [0, 1]) 851 852 def testSO_LINGER(self): 853 self.test_tcp_client = 1 854 self.test_tcp_server = 1 855 off = struct.pack('ii', 0, 0) 856 on_2_seconds = struct.pack('ii', 1, 2) 857 self._testOption(socket.SOL_SOCKET, socket.SO_LINGER, [off, on_2_seconds]) 858 self._testInheritedOption(socket.SOL_SOCKET, socket.SO_LINGER, [off, on_2_seconds]) 859 860 def testSO_OOBINLINE(self): 861 self.test_tcp_client = 1 862 self.test_tcp_server = 1 863 self._testOption(socket.SOL_SOCKET, socket.SO_OOBINLINE, [0, 1]) 864 self._testInheritedOption(socket.SOL_SOCKET, socket.SO_OOBINLINE, [0, 1]) 865 866 def testSO_RCVBUF(self): 867 self.test_udp = 1 868 self.test_tcp_client = 1 869 self.test_tcp_server = 1 870 self._testOption(socket.SOL_SOCKET, socket.SO_RCVBUF, [1024, 4096, 16384]) 871 self._testInheritedOption(socket.SOL_SOCKET, socket.SO_RCVBUF, [1024, 4096, 16384]) 872 873 def testSO_REUSEADDR(self): 874 self.test_udp = 1 875 self.test_tcp_client = 1 876 self.test_tcp_server = 1 877 self._testOption(socket.SOL_SOCKET, socket.SO_REUSEADDR, [0, 1]) 878 self._testInheritedOption(socket.SOL_SOCKET, socket.SO_REUSEADDR, [0, 1]) 879 880 def testSO_SNDBUF(self): 881 self.test_udp = 1 882 self.test_tcp_client = 1 883 self.test_tcp_server = 1 884 self._testOption(socket.SOL_SOCKET, socket.SO_SNDBUF, [1024, 4096, 16384]) 885 self._testInheritedOption(socket.SOL_SOCKET, socket.SO_SNDBUF, [1024, 4096, 16384]) 886 887 def testSO_TIMEOUT(self): 888 self.test_udp = 1 889 self.test_tcp_client = 1 890 self.test_tcp_server = 1 891 self._testOption(socket.SOL_SOCKET, socket.SO_TIMEOUT, [0, 1, 1000]) 892 # We don't test inheritance here because both server and client sockets have SO_TIMEOUT 893 # but it doesn't inherit. 894 895 def testTCP_NODELAY(self): 896 self.test_tcp_client = 1 897 self.test_tcp_server = 1 898 self._testOption(socket.IPPROTO_TCP, socket.TCP_NODELAY, [0, 1]) 899 self._testInheritedOption(socket.IPPROTO_TCP, socket.TCP_NODELAY, [0, 1]) 900 901class TestPseudoOptions(unittest.TestCase): 902 903 def testSO_ACCEPTCONN(self): 904 for socket_type, listen, expected_result in [ 905 (socket.SOCK_STREAM, 0, 0), 906 (socket.SOCK_STREAM, 1, 1), 907 (socket.SOCK_DGRAM, 0, Exception), 908 ]: 909 s = socket.socket(socket.AF_INET, socket_type) 910 if listen: 911 s.listen(1) 912 try: 913 result = s.getsockopt(socket.SOL_SOCKET, socket.SO_ACCEPTCONN) 914 if expected_result is not Exception: 915 self.failUnlessEqual(result, expected_result) 916 except socket.error, se: 917 if expected_result is Exception: 918 if se[0] != errno.ENOPROTOOPT: 919 self.fail("getsockopt(SO_ACCEPTCONN) on wrong socket type raised wrong exception: %s" % str(se)) 920 else: 921 self.fail("getsocket(SO_ACCEPTCONN) on valid socket type should not have raised exception: %s" % (str(se))) 922 923 def testSO_ERROR(self): 924 for socket_type in [socket.SOCK_STREAM, socket.SOCK_DGRAM]: 925 s = socket.socket(socket.AF_INET, socket_type) 926 self.failUnlessEqual(s.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR), 0) 927 try: 928 # Now cause an error 929 s.connect(("localhost", 100000)) 930 self.fail("Operation '%s' that should have failed to generate SO_ERROR did not" % operation) 931 except socket.error, se: 932 so_error = s.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) 933 self.failUnlessEqual(so_error, se[0]) 934 # Now retrieve the option again - it should be zero 935 self.failUnlessEqual(s.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR), 0) 936 937 def testSO_TYPE(self): 938 for socket_type in [socket.SOCK_STREAM, socket.SOCK_DGRAM]: 939 s = socket.socket(socket.AF_INET, socket_type) 940 self.failUnlessEqual(s.getsockopt(socket.SOL_SOCKET, socket.SO_TYPE), socket_type) 941 942class TestUnsupportedOptions(TestSocketOptions): 943 944 def testSO_DEBUG(self): 945 self.failUnless(hasattr(socket, 'SO_DEBUG')) 946 947 def testSO_DONTROUTE(self): 948 self.failUnless(hasattr(socket, 'SO_DONTROUTE')) 949 950 def testSO_EXCLUSIVEADDRUSE(self): 951 # this is an MS specific option that will not be appearing on java 952 # http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6421091 953 # http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6402335 954 self.failUnless(hasattr(socket, 'SO_EXCLUSIVEADDRUSE')) 955 956 def testSO_RCVLOWAT(self): 957 self.failUnless(hasattr(socket, 'SO_RCVLOWAT')) 958 959 def testSO_RCVTIMEO(self): 960 self.failUnless(hasattr(socket, 'SO_RCVTIMEO')) 961 962 def testSO_REUSEPORT(self): 963 # not yet supported on java 964 # http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6432031 965 self.failUnless(hasattr(socket, 'SO_REUSEPORT')) 966 967 def testSO_SNDLOWAT(self): 968 self.failUnless(hasattr(socket, 'SO_SNDLOWAT')) 969 970 def testSO_SNDTIMEO(self): 971 self.failUnless(hasattr(socket, 'SO_SNDTIMEO')) 972 973 def testSO_USELOOPBACK(self): 974 self.failUnless(hasattr(socket, 'SO_USELOOPBACK')) 975 976class BasicTCPTest(SocketConnectedTest): 977 978 def __init__(self, methodName='runTest'): 979 SocketConnectedTest.__init__(self, methodName=methodName) 980 981 def testRecv(self): 982 # Testing large receive over TCP 983 msg = self.cli_conn.recv(1024) 984 self.assertEqual(msg, MSG) 985 986 def _testRecv(self): 987 self.serv_conn.send(MSG) 988 989 def testRecvTimeoutMode(self): 990 # Do this test in timeout mode, because the code path is different 991 self.cli_conn.settimeout(10) 992 msg = self.cli_conn.recv(1024) 993 self.assertEqual(msg, MSG) 994 995 def _testRecvTimeoutMode(self): 996 self.serv_conn.settimeout(10) 997 self.serv_conn.send(MSG) 998 999 def testOverFlowRecv(self): 1000 # Testing receive in chunks over TCP 1001 seg1 = self.cli_conn.recv(len(MSG) - 3) 1002 seg2 = self.cli_conn.recv(1024) 1003 msg = seg1 + seg2 1004 self.assertEqual(msg, MSG) 1005 1006 def _testOverFlowRecv(self): 1007 self.serv_conn.send(MSG) 1008 1009 def testRecvFrom(self): 1010 # Testing large recvfrom() over TCP 1011 msg, addr = self.cli_conn.recvfrom(1024) 1012 self.assertEqual(msg, MSG) 1013 1014 def _testRecvFrom(self): 1015 self.serv_conn.send(MSG) 1016 1017 def testOverFlowRecvFrom(self): 1018 # Testing recvfrom() in chunks over TCP 1019 seg1, addr = self.cli_conn.recvfrom(len(MSG)-3) 1020 seg2, addr = self.cli_conn.recvfrom(1024) 1021 msg = seg1 + seg2 1022 self.assertEqual(msg, MSG) 1023 1024 def _testOverFlowRecvFrom(self): 1025 self.serv_conn.send(MSG) 1026 1027 def testSendAll(self): 1028 # Testing sendall() with a 2048 byte string over TCP 1029 msg = '' 1030 while 1: 1031 read = self.cli_conn.recv(1024) 1032 if not read: 1033 break 1034 msg += read 1035 self.assertEqual(msg, 'f' * 2048) 1036 1037 def _testSendAll(self): 1038 big_chunk = 'f' * 2048 1039 self.serv_conn.sendall(big_chunk) 1040 1041 def testFromFd(self): 1042 # Testing fromfd() 1043 if not hasattr(socket, "fromfd"): 1044 return # On Windows, this doesn't exist 1045 fd = self.cli_conn.fileno() 1046 sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM) 1047 msg = sock.recv(1024) 1048 self.assertEqual(msg, MSG) 1049 1050 def _testFromFd(self): 1051 self.serv_conn.send(MSG) 1052 1053 def testShutdown(self): 1054 # Testing shutdown() 1055 msg = self.cli_conn.recv(1024) 1056 self.assertEqual(msg, MSG) 1057 1058 def _testShutdown(self): 1059 self.serv_conn.send(MSG) 1060 self.serv_conn.shutdown(2) 1061 1062 def testSendAfterRemoteClose(self): 1063 self.cli_conn.close() 1064 1065 def _testSendAfterRemoteClose(self): 1066 for x in range(5): 1067 try: 1068 self.serv_conn.send("spam") 1069 except socket.error, se: 1070 self.failUnlessEqual(se[0], errno.ECONNRESET) 1071 return 1072 except Exception, x: 1073 self.fail("Sending on remotely closed socket raised wrong exception: %s" % x) 1074 time.sleep(0.5) 1075 self.fail("Sending on remotely closed socket should have raised exception") 1076 1077 def testDup(self): 1078 msg = self.cli_conn.recv(len(MSG)) 1079 self.assertEqual(msg, MSG) 1080 1081 dup_conn = self.cli_conn.dup() 1082 msg = dup_conn.recv(len('and ' + MSG)) 1083 self.assertEqual(msg, 'and ' + MSG) 1084 1085 def _testDup(self): 1086 self.serv_conn.send(MSG) 1087 self.serv_conn.send('and ' + MSG) 1088 1089class UDPBindTest(unittest.TestCase): 1090 1091 HOST = HOST 1092 PORT = PORT 1093 1094 def setUp(self): 1095 self.sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) 1096 1097 def testBindSpecific(self): 1098 self.sock.bind( (self.HOST, self.PORT) ) # Use a specific port 1099 actual_port = self.sock.getsockname()[1] 1100 self.failUnless(actual_port == self.PORT, 1101 "Binding to specific port number should have returned same number: %d != %d" % (actual_port, self.PORT)) 1102 1103 def testBindEphemeral(self): 1104 self.sock.bind( (self.HOST, 0) ) # let system choose a free port 1105 self.failUnless(self.sock.getsockname()[1] != 0, "Binding to port zero should have allocated an ephemeral port number") 1106 1107 def testShutdown(self): 1108 self.sock.bind( (self.HOST, self.PORT) ) 1109 self.sock.shutdown(socket.SHUT_RDWR) 1110 1111 def tearDown(self): 1112 self.sock.close() 1113 1114class BasicUDPTest(ThreadedUDPSocketTest): 1115 1116 def __init__(self, methodName='runTest'): 1117 ThreadedUDPSocketTest.__init__(self, methodName=methodName) 1118 1119 def testSendtoAndRecv(self): 1120 # Testing sendto() and recv() over UDP 1121 msg = self.serv.recv(len(MSG)) 1122 self.assertEqual(msg, MSG) 1123 1124 def _testSendtoAndRecv(self): 1125 self.cli.sendto(MSG, 0, (self.HOST, self.PORT)) 1126 1127 def testSendtoAndRecvTimeoutMode(self): 1128 # Need to test again in timeout mode, which follows 1129 # a different code path 1130 self.serv.settimeout(10) 1131 msg = self.serv.recv(len(MSG)) 1132 self.assertEqual(msg, MSG) 1133 1134 def _testSendtoAndRecvTimeoutMode(self): 1135 self.cli.settimeout(10) 1136 self.cli.sendto(MSG, 0, (self.HOST, self.PORT)) 1137 1138 def testSendAndRecv(self): 1139 # Testing send() and recv() over connect'ed UDP 1140 msg = self.serv.recv(len(MSG)) 1141 self.assertEqual(msg, MSG) 1142 1143 def _testSendAndRecv(self): 1144 self.cli.connect( (self.HOST, self.PORT) ) 1145 self.cli.send(MSG, 0) 1146 1147 def testSendAndRecvTimeoutMode(self): 1148 # Need to test again in timeout mode, which follows 1149 # a different code path 1150 self.serv.settimeout(10) 1151 # Testing send() and recv() over connect'ed UDP 1152 msg = self.serv.recv(len(MSG)) 1153 self.assertEqual(msg, MSG) 1154 1155 def _testSendAndRecvTimeoutMode(self): 1156 self.cli.connect( (self.HOST, self.PORT) ) 1157 self.cli.settimeout(10) 1158 self.cli.send(MSG, 0) 1159 1160 def testRecvFrom(self): 1161 # Testing recvfrom() over UDP 1162 msg, addr = self.serv.recvfrom(len(MSG)) 1163 self.assertEqual(msg, MSG) 1164 1165 def _testRecvFrom(self): 1166 self.cli.sendto(MSG, 0, (self.HOST, self.PORT)) 1167 1168 def testRecvFromTimeoutMode(self): 1169 # Need to test again in timeout mode, which follows 1170 # a different code path 1171 self.serv.settimeout(10) 1172 msg, addr = self.serv.recvfrom(len(MSG)) 1173 self.assertEqual(msg, MSG) 1174 1175 def _testRecvFromTimeoutMode(self): 1176 self.cli.settimeout(10) 1177 self.cli.sendto(MSG, 0, (self.HOST, self.PORT)) 1178 1179 def testSendtoEightBitSafe(self): 1180 # This test is necessary because java only supports signed bytes 1181 msg = self.serv.recv(len(EIGHT_BIT_MSG)) 1182 self.assertEqual(msg, EIGHT_BIT_MSG) 1183 1184 def _testSendtoEightBitSafe(self): 1185 self.cli.sendto(EIGHT_BIT_MSG, 0, (self.HOST, self.PORT)) 1186 1187 def testSendtoEightBitSafeTimeoutMode(self): 1188 # Need to test again in timeout mode, which follows 1189 # a different code path 1190 self.serv.settimeout(10) 1191 msg = self.serv.recv(len(EIGHT_BIT_MSG)) 1192 self.assertEqual(msg, EIGHT_BIT_MSG) 1193 1194 def _testSendtoEightBitSafeTimeoutMode(self): 1195 self.cli.settimeout(10) 1196 self.cli.sendto(EIGHT_BIT_MSG, 0, (self.HOST, self.PORT)) 1197 1198class UDPBroadcastTest(ThreadedUDPSocketTest): 1199 1200 def setUp(self): 1201 self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 1202 self.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 1203 1204 def testBroadcast(self): 1205 self.serv.bind( ("", self.PORT) ) 1206 msg = self.serv.recv(len(EIGHT_BIT_MSG)) 1207 self.assertEqual(msg, EIGHT_BIT_MSG) 1208 1209 def _testBroadcast(self): 1210 self.cli.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) 1211 self.cli.sendto(EIGHT_BIT_MSG, ("<broadcast>", self.PORT) ) 1212 1213class BasicSocketPairTest(SocketPairTest): 1214 1215 def __init__(self, methodName='runTest'): 1216 SocketPairTest.__init__(self, methodName=methodName) 1217 1218 def testRecv(self): 1219 msg = self.serv.recv(1024) 1220 self.assertEqual(msg, MSG) 1221 1222 def _testRecv(self): 1223 self.cli.send(MSG) 1224 1225 def testSend(self): 1226 self.serv.send(MSG) 1227 1228 def _testSend(self): 1229 msg = self.cli.recv(1024) 1230 self.assertEqual(msg, MSG) 1231 1232class NonBlockingTCPServerTests(SocketTCPTest): 1233 1234 def testSetBlocking(self): 1235 # Testing whether set blocking works 1236 self.serv.setblocking(0) 1237 start = time.time() 1238 try: 1239 self.serv.accept() 1240 except socket.error: 1241 pass 1242 end = time.time() 1243 self.assert_((end - start) < 1.0, "Error setting non-blocking mode.") 1244 1245 def testGetBlocking(self): 1246 # Testing whether set blocking works 1247 self.serv.setblocking(0) 1248 self.failUnless(not self.serv.getblocking(), "Getblocking return true instead of false") 1249 self.serv.setblocking(1) 1250 self.failUnless(self.serv.getblocking(), "Getblocking return false instead of true") 1251 1252 def testAcceptNoConnection(self): 1253 # Testing non-blocking accept returns immediately when no connection 1254 self.serv.setblocking(0) 1255 try: 1256 conn, addr = self.serv.accept() 1257 except socket.error: 1258 pass 1259 else: 1260 self.fail("Error trying to do non-blocking accept.") 1261 1262class NonBlockingTCPTests(ThreadedTCPSocketTest): 1263 1264 def __init__(self, methodName='runTest'): 1265 ThreadedTCPSocketTest.__init__(self, methodName=methodName) 1266 1267 def testAcceptConnection(self): 1268 # Testing non-blocking accept works when connection present 1269 self.serv.setblocking(0) 1270 read, write, err = select.select([self.serv], [], []) 1271 if self.serv in read: 1272 conn, addr = self.serv.accept() 1273 else: 1274 self.fail("Error trying to do accept after select: server socket was not in 'read'able list") 1275 1276 def _testAcceptConnection(self): 1277 # Make a connection to the server 1278 self.cli.connect((self.HOST, self.PORT)) 1279 1280 # 1281 # AMAK: 20070311 1282 # Introduced a new test for non-blocking connect 1283 # Renamed old testConnect to testBlockingConnect 1284 # 1285 1286 def testBlockingConnect(self): 1287 # Testing blocking connect 1288 conn, addr = self.serv.accept() 1289 1290 def _testBlockingConnect(self): 1291 # Testing blocking connect 1292 self.cli.settimeout(10) 1293 self.cli.connect((self.HOST, self.PORT)) 1294 1295 def testNonBlockingConnect(self): 1296 # Testing non-blocking connect 1297 conn, addr = self.serv.accept() 1298 1299 def _testNonBlockingConnect(self): 1300 # Testing non-blocking connect 1301 self.cli.setblocking(0) 1302 result = self.cli.connect_ex((self.HOST, self.PORT)) 1303 rfds, wfds, xfds = select.select([], [self.cli], []) 1304 self.failUnless(self.cli in wfds) 1305 try: 1306 self.cli.send(MSG) 1307 except socket.error: 1308 self.fail("Sending on connected socket should not have raised socket.error") 1309 1310 # 1311 # AMAK: 20070518 1312 # Introduced a new test for connect with bind to specific local address 1313 # 1314 1315 def testConnectWithLocalBind(self): 1316 # Test blocking connect 1317 conn, addr = self.serv.accept() 1318 1319 def _testConnectWithLocalBind(self): 1320 # Testing blocking connect with local bind 1321 cli_port = self.PORT - 1 1322 while True: 1323 # Keep trying until a local port is available 1324 self.cli.settimeout(1) 1325 self.cli.bind( (self.HOST, cli_port) ) 1326 try: 1327 self.cli.connect((self.HOST, self.PORT)) 1328 …
Large files files are truncated, but you can click here to view the full file