PageRenderTime 66ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 1ms

/Lib/test/test_socket.py

https://bitbucket.org/noghriw/jython
Python | 2252 lines | 2003 code | 152 blank | 97 comment | 142 complexity | 628428ee780201490e55b7f1c8f61152 MD5 | raw file
Possible License(s): Apache-2.0, BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

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

Large files files are truncated, but you can click here to view the full file