PageRenderTime 108ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 1ms

/Lib/test/test_socket.py

https://bitbucket.org/shashank/jython
Python | 2508 lines | 2249 code | 155 blank | 104 comment | 170 complexity | 8b43af09cc79562df502e66d3bd8843e MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0
  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, expected_name_starts in [
  224. ('IPPROTO_ICMP', ['IPPROTO_']),
  225. ('IPPROTO_TCP', ['IPPROTO_']),
  226. ('IPPROTO_UDP', ['IPPROTO_']),
  227. ('SO_BROADCAST', ['SO_', 'TCP_']),
  228. ('SO_KEEPALIVE', ['SO_', 'TCP_']),
  229. ('SO_ACCEPTCONN', ['SO_', 'TCP_']),
  230. ('SO_DEBUG', ['SO_', 'TCP_']),
  231. ('SOCK_DGRAM', ['SOCK_']),
  232. ('SOCK_RAW', ['SOCK_']),
  233. ('SOL_SOCKET', ['SOL_', 'IPPROTO_']),
  234. ('TCP_NODELAY', ['SO_', 'TCP_']),
  235. ]:
  236. self.failUnlessEqual(socket._constant_to_name(getattr(socket, name), expected_name_starts), name)
  237. def testHostnameRes(self):
  238. # Testing hostname resolution mechanisms
  239. hostname = socket.gethostname()
  240. self.assert_(isinstance(hostname, str))
  241. try:
  242. ip = socket.gethostbyname(hostname)
  243. self.assert_(isinstance(ip, str))
  244. except socket.error:
  245. # Probably name lookup wasn't set up right; skip this test
  246. self.fail("Probably name lookup wasn't set up right; skip testHostnameRes.gethostbyname")
  247. return
  248. self.assert_(ip.find('.') >= 0, "Error resolving host to ip.")
  249. try:
  250. hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
  251. self.assert_(isinstance(hname, str))
  252. for hosts in aliases, ipaddrs:
  253. self.assert_(all(isinstance(host, str) for host in hosts))
  254. except socket.error:
  255. # Probably a similar problem as above; skip this test
  256. self.fail("Probably name lookup wasn't set up right; skip testHostnameRes.gethostbyaddr")
  257. return
  258. all_host_names = [hostname, hname] + aliases
  259. fqhn = socket.getfqdn()
  260. self.assert_(isinstance(fqhn, str))
  261. if not fqhn in all_host_names:
  262. self.fail("Error testing host resolution mechanisms.")
  263. def testRefCountGetNameInfo(self):
  264. # Testing reference count for getnameinfo
  265. import sys
  266. if hasattr(sys, "getrefcount"):
  267. try:
  268. # On some versions, this loses a reference
  269. orig = sys.getrefcount(__name__)
  270. socket.getnameinfo(__name__,0)
  271. except SystemError:
  272. if sys.getrefcount(__name__) <> orig:
  273. self.fail("socket.getnameinfo loses a reference")
  274. def testInterpreterCrash(self):
  275. if sys.platform[:4] == 'java': return
  276. # Making sure getnameinfo doesn't crash the interpreter
  277. try:
  278. # On some versions, this crashes the interpreter.
  279. socket.getnameinfo(('x', 0, 0, 0), 0)
  280. except socket.error:
  281. pass
  282. # Need to implement binary AND for ints and longs
  283. def testNtoH(self):
  284. if sys.platform[:4] == 'java': return # problems with int & long
  285. # This just checks that htons etc. are their own inverse,
  286. # when looking at the lower 16 or 32 bits.
  287. sizes = {socket.htonl: 32, socket.ntohl: 32,
  288. socket.htons: 16, socket.ntohs: 16}
  289. for func, size in sizes.items():
  290. mask = (1L<<size) - 1
  291. for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210):
  292. self.assertEqual(i & mask, func(func(i&mask)) & mask)
  293. swapped = func(mask)
  294. self.assertEqual(swapped & mask, mask)
  295. self.assertRaises(OverflowError, func, 1L<<34)
  296. def testGetServBy(self):
  297. eq = self.assertEqual
  298. # Find one service that exists, then check all the related interfaces.
  299. # I've ordered this by protocols that have both a tcp and udp
  300. # protocol, at least for modern Linuxes.
  301. if sys.platform in ('linux2', 'freebsd4', 'freebsd5', 'freebsd6',
  302. 'darwin') or is_bsd:
  303. # avoid the 'echo' service on this platform, as there is an
  304. # assumption breaking non-standard port/protocol entry
  305. services = ('daytime', 'qotd', 'domain')
  306. else:
  307. services = ('echo', 'daytime', 'domain')
  308. for service in services:
  309. try:
  310. port = socket.getservbyname(service, 'tcp')
  311. break
  312. except socket.error:
  313. pass
  314. else:
  315. raise socket.error
  316. # Try same call with optional protocol omitted
  317. port2 = socket.getservbyname(service)
  318. eq(port, port2)
  319. # Try udp, but don't barf it it doesn't exist
  320. try:
  321. udpport = socket.getservbyname(service, 'udp')
  322. except socket.error:
  323. udpport = None
  324. else:
  325. eq(udpport, port)
  326. # Now make sure the lookup by port returns the same service name
  327. eq(socket.getservbyport(port2), service)
  328. eq(socket.getservbyport(port, 'tcp'), service)
  329. if udpport is not None:
  330. eq(socket.getservbyport(udpport, 'udp'), service)
  331. def testGetServByExceptions(self):
  332. # First getservbyname
  333. try:
  334. result = socket.getservbyname("nosuchservice")
  335. except socket.error:
  336. pass
  337. except Exception, x:
  338. self.fail("getservbyname raised wrong exception for non-existent service: %s" % str(x))
  339. else:
  340. self.fail("getservbyname failed to raise exception for non-existent service: %s" % str(result))
  341. # Now getservbyport
  342. try:
  343. result = socket.getservbyport(55555)
  344. except socket.error:
  345. pass
  346. except Exception, x:
  347. self.fail("getservbyport raised wrong exception for unknown port: %s" % str(x))
  348. else:
  349. self.fail("getservbyport failed to raise exception for unknown port: %s" % str(result))
  350. def testGetProtoByName(self):
  351. self.failUnlessEqual(socket.IPPROTO_TCP, socket.getprotobyname("tcp"))
  352. self.failUnlessEqual(socket.IPPROTO_UDP, socket.getprotobyname("udp"))
  353. try:
  354. result = socket.getprotobyname("nosuchproto")
  355. except socket.error:
  356. pass
  357. except Exception, x:
  358. self.fail("getprotobyname raised wrong exception for unknown protocol: %s" % str(x))
  359. else:
  360. self.fail("getprotobyname failed to raise exception for unknown protocol: %s" % str(result))
  361. def testDefaultTimeout(self):
  362. # Testing default timeout
  363. # The default timeout should initially be None
  364. self.assertEqual(socket.getdefaulttimeout(), None)
  365. s = socket.socket()
  366. self.assertEqual(s.gettimeout(), None)
  367. s.close()
  368. # Set the default timeout to 10, and see if it propagates
  369. socket.setdefaulttimeout(10)
  370. self.assertEqual(socket.getdefaulttimeout(), 10)
  371. s = socket.socket()
  372. self.assertEqual(s.gettimeout(), 10)
  373. s.close()
  374. # Reset the default timeout to None, and see if it propagates
  375. socket.setdefaulttimeout(None)
  376. self.assertEqual(socket.getdefaulttimeout(), None)
  377. s = socket.socket()
  378. self.assertEqual(s.gettimeout(), None)
  379. s.close()
  380. # Check that setting it to an invalid value raises ValueError
  381. self.assertRaises(ValueError, socket.setdefaulttimeout, -1)
  382. # Check that setting it to an invalid type raises TypeError
  383. self.assertRaises(TypeError, socket.setdefaulttimeout, "spam")
  384. def testIPv4toString(self):
  385. if not hasattr(socket, 'inet_pton'):
  386. return # No inet_pton() on this platform
  387. from socket import inet_aton as f, inet_pton, AF_INET
  388. g = lambda a: inet_pton(AF_INET, a)
  389. self.assertEquals('\x00\x00\x00\x00', f('0.0.0.0'))
  390. self.assertEquals('\xff\x00\xff\x00', f('255.0.255.0'))
  391. self.assertEquals('\xaa\xaa\xaa\xaa', f('170.170.170.170'))
  392. self.assertEquals('\x01\x02\x03\x04', f('1.2.3.4'))
  393. self.assertEquals('\x00\x00\x00\x00', g('0.0.0.0'))
  394. self.assertEquals('\xff\x00\xff\x00', g('255.0.255.0'))
  395. self.assertEquals('\xaa\xaa\xaa\xaa', g('170.170.170.170'))
  396. def testIPv6toString(self):
  397. if not hasattr(socket, 'inet_pton'):
  398. return # No inet_pton() on this platform
  399. try:
  400. from socket import inet_pton, AF_INET6, has_ipv6
  401. if not has_ipv6:
  402. return
  403. except ImportError:
  404. return
  405. f = lambda a: inet_pton(AF_INET6, a)
  406. self.assertEquals('\x00' * 16, f('::'))
  407. self.assertEquals('\x00' * 16, f('0::0'))
  408. self.assertEquals('\x00\x01' + '\x00' * 14, f('1::'))
  409. self.assertEquals(
  410. '\x45\xef\x76\xcb\x00\x1a\x56\xef\xaf\xeb\x0b\xac\x19\x24\xae\xae',
  411. f('45ef:76cb:1a:56ef:afeb:bac:1924:aeae')
  412. )
  413. def test_inet_pton_exceptions(self):
  414. if not hasattr(socket, 'inet_pton'):
  415. return # No inet_pton() on this platform
  416. try:
  417. socket.inet_pton(socket.AF_UNSPEC, "doesntmatter")
  418. except socket.error, se:
  419. self.failUnlessEqual(se[0], errno.EAFNOSUPPORT)
  420. except Exception, x:
  421. self.fail("inet_pton raised wrong exception for incorrect address family AF_UNSPEC: %s" % str(x))
  422. try:
  423. socket.inet_pton(socket.AF_INET, "1.2.3.")
  424. except socket.error, se:
  425. pass
  426. except Exception, x:
  427. self.fail("inet_pton raised wrong exception for invalid AF_INET address: %s" % str(x))
  428. try:
  429. socket.inet_pton(socket.AF_INET6, ":::")
  430. except socket.error, se:
  431. pass
  432. except Exception, x:
  433. self.fail("inet_pton raised wrong exception for invalid AF_INET6 address: %s" % str(x))
  434. def testStringToIPv4(self):
  435. if not hasattr(socket, 'inet_ntop'):
  436. return # No inet_ntop() on this platform
  437. from socket import inet_ntoa as f, inet_ntop, AF_INET
  438. g = lambda a: inet_ntop(AF_INET, a)
  439. self.assertEquals('1.0.1.0', f('\x01\x00\x01\x00'))
  440. self.assertEquals('170.85.170.85', f('\xaa\x55\xaa\x55'))
  441. self.assertEquals('255.255.255.255', f('\xff\xff\xff\xff'))
  442. self.assertEquals('1.2.3.4', f('\x01\x02\x03\x04'))
  443. self.assertEquals('1.0.1.0', g('\x01\x00\x01\x00'))
  444. self.assertEquals('170.85.170.85', g('\xaa\x55\xaa\x55'))
  445. self.assertEquals('255.255.255.255', g('\xff\xff\xff\xff'))
  446. def testStringToIPv6(self):
  447. if not hasattr(socket, 'inet_ntop'):
  448. return # No inet_ntop() on this platform
  449. try:
  450. from socket import inet_ntop, AF_INET6, has_ipv6
  451. if not has_ipv6:
  452. return
  453. except ImportError:
  454. return
  455. f = lambda a: inet_ntop(AF_INET6, a)
  456. # self.assertEquals('::', f('\x00' * 16))
  457. # self.assertEquals('::1', f('\x00' * 15 + '\x01'))
  458. # java.net.InetAddress always return the full unabbreviated form
  459. self.assertEquals('0:0:0:0:0:0:0:0', f('\x00' * 16))
  460. self.assertEquals('0:0:0:0:0:0:0:1', f('\x00' * 15 + '\x01'))
  461. self.assertEquals(
  462. 'aef:b01:506:1001:ffff:9997:55:170',
  463. f('\x0a\xef\x0b\x01\x05\x06\x10\x01\xff\xff\x99\x97\x00\x55\x01\x70')
  464. )
  465. def test_inet_ntop_exceptions(self):
  466. if not hasattr(socket, 'inet_ntop'):
  467. return # No inet_ntop() on this platform
  468. valid_address = '\x01\x01\x01\x01'
  469. invalid_address = '\x01\x01\x01\x01\x01'
  470. try:
  471. socket.inet_ntop(socket.AF_UNSPEC, valid_address)
  472. except ValueError, v:
  473. pass
  474. except Exception, x:
  475. self.fail("inet_ntop raised wrong exception for incorrect address family AF_UNSPEC: %s" % str(x))
  476. try:
  477. socket.inet_ntop(socket.AF_INET, invalid_address)
  478. except ValueError, v:
  479. pass
  480. except Exception, x:
  481. self.fail("inet_ntop raised wrong exception for invalid AF_INET address: %s" % str(x))
  482. try:
  483. socket.inet_ntop(socket.AF_INET6, invalid_address)
  484. except ValueError, v:
  485. pass
  486. except Exception, x:
  487. self.fail("inet_ntop raised wrong exception for invalid AF_INET address: %s" % str(x))
  488. # XXX The following don't test module-level functionality...
  489. def testSockName(self):
  490. # Testing getsockname()
  491. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  492. sock.bind(("0.0.0.0", PORT+1))
  493. name = sock.getsockname()
  494. self.assertEqual(name, ("0.0.0.0", PORT+1))
  495. def testSockAttributes(self):
  496. # Testing required attributes
  497. for family in [socket.AF_INET, socket.AF_INET6]:
  498. for sock_type in [socket.SOCK_STREAM, socket.SOCK_DGRAM]:
  499. s = socket.socket(family, sock_type)
  500. self.assertEqual(s.family, family)
  501. self.assertEqual(s.type, sock_type)
  502. if sock_type == socket.SOCK_STREAM:
  503. self.assertEqual(s.proto, socket.IPPROTO_TCP)
  504. else:
  505. self.assertEqual(s.proto, socket.IPPROTO_UDP)
  506. def testGetSockOpt(self):
  507. # Testing getsockopt()
  508. # We know a socket should start without reuse==0
  509. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  510. reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
  511. self.failIf(reuse != 0, "initial mode is reuse")
  512. def testSetSockOpt(self):
  513. # Testing setsockopt()
  514. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  515. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  516. reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
  517. self.failIf(reuse == 0, "failed to set reuse mode")
  518. def testSendAfterClose(self):
  519. # testing send() after close() with timeout
  520. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  521. sock.settimeout(1)
  522. sock.close()
  523. self.assertRaises(socket.error, sock.send, "spam")
  524. class IPAddressTests(unittest.TestCase):
  525. def testValidIpV4Addresses(self):
  526. for a in [
  527. "0.0.0.1",
  528. "1.0.0.1",
  529. "127.0.0.1",
  530. "255.12.34.56",
  531. "255.255.255.255",
  532. ]:
  533. self.failUnless(socket.is_ipv4_address(a), "is_ipv4_address failed for valid IPV4 address '%s'" % a)
  534. self.failUnless(socket.is_ip_address(a), "is_ip_address failed for valid IPV4 address '%s'" % a)
  535. def testInvalidIpV4Addresses(self):
  536. for a in [
  537. "99.2",
  538. "99.2.4",
  539. "-10.1.2.3",
  540. "256.0.0.0",
  541. "0.256.0.0",
  542. "0.0.256.0",
  543. "0.0.0.256",
  544. "255.24.x.100",
  545. "255.24.-1.128",
  546. "255.24.-1.128.",
  547. "255.0.0.999",
  548. ]:
  549. self.failUnless(not socket.is_ipv4_address(a), "not is_ipv4_address failed for invalid IPV4 address '%s'" % a)
  550. self.failUnless(not socket.is_ip_address(a), "not is_ip_address failed for invalid IPV4 address '%s'" % a)
  551. def testValidIpV6Addresses(self):
  552. for a in [
  553. "::",
  554. "::1",
  555. "fe80::1",
  556. "::192.168.1.1",
  557. "0:0:0:0:0:0:0:0",
  558. "1080::8:800:2C:4A",
  559. "FEC0:0:0:0:0:0:0:1",
  560. "::FFFF:192.168.1.1",
  561. "abcd:ef:111:f123::1",
  562. "1138:0:0:0:8:80:800:417A",
  563. "fecc:face::b00c:f001:fedc:fedd",
  564. "CaFe:BaBe:dEAd:BeeF:12:345:6789:abcd",
  565. ]:
  566. self.failUnless(socket.is_ipv6_address(a), "is_ipv6_address failed for valid IPV6 address '%s'" % a)
  567. self.failUnless(socket.is_ip_address(a), "is_ip_address failed for valid IPV6 address '%s'" % a)
  568. def testInvalidIpV6Addresses(self):
  569. for a in [
  570. "2001:db8:::192.0.2.1", # from RFC 5954
  571. "CaFe:BaBe:dEAd:BeeF:12:345:6789:abcd:",
  572. "CaFe:BaBe:dEAd:BeeF:12:345:6789:abcd:ef",
  573. "CaFFe:1a77e:dEAd:BeeF:12:345:6789:abcd",
  574. ]:
  575. self.failUnless(not socket.is_ipv6_address(a), "not is_ipv6_address failed for invalid IPV6 address '%s'" % a)
  576. self.failUnless(not socket.is_ip_address(a), "not is_ip_address failed for invalid IPV6 address '%s'" % a)
  577. def testRFC5952(self):
  578. for a in [
  579. "2001:db8::",
  580. "2001:db8::1",
  581. "2001:db8:0::1",
  582. "2001:db8:0:0::1",
  583. "2001:db8:0:0:0::1",
  584. "2001:DB8:0:0:1::1",
  585. "2001:db8:0:0:1::1",
  586. "2001:db8::1:0:0:1",
  587. "2001:0db8::1:0:0:1",
  588. "2001:db8::0:1:0:0:1",
  589. "2001:db8:0:0:1:0:0:1",
  590. "2001:db8:0000:0:1::1",
  591. "2001:db8::aaaa:0:0:1",
  592. "2001:db8:0:0:aaaa::1",
  593. "2001:0db8:0:0:1:0:0:1",
  594. "2001:db8:aaaa:bbbb:cccc:dddd::1",
  595. "2001:db8:aaaa:bbbb:cccc:dddd:0:1",
  596. "2001:db8:aaaa:bbbb:cccc:dddd:eeee:1",
  597. "2001:db8:aaaa:bbbb:cccc:dddd:eeee:01",
  598. "2001:db8:aaaa:bbbb:cccc:dddd:eeee:001",
  599. "2001:db8:aaaa:bbbb:cccc:dddd:eeee:0001",
  600. "2001:db8:aaaa:bbbb:cccc:dddd:eeee:aaaa",
  601. "2001:db8:aaaa:bbbb:cccc:dddd:eeee:AAAA",
  602. "2001:db8:aaaa:bbbb:cccc:dddd:eeee:AaAa",
  603. ]:
  604. self.failUnless(socket.is_ipv6_address(a), "is_ipv6_address failed for valid RFC 5952 IPV6 address '%s'" % a)
  605. self.failUnless(socket.is_ip_address(a), "is_ip_address failed for valid RFC 5952 IPV6 address '%s'" % a)
  606. class TestSocketOptions(unittest.TestCase):
  607. def setUp(self):
  608. self.test_udp = self.test_tcp_client = self.test_tcp_server = 0
  609. def _testSetAndGetOption(self, sock, level, option, values):
  610. for expected_value in values:
  611. sock.setsockopt(level, option, expected_value)
  612. retrieved_value = sock.getsockopt(level, option)
  613. msg = "Retrieved option(%s, %s) value %s != %s(value set)" % (level, option, retrieved_value, expected_value)
  614. if option == socket.SO_RCVBUF:
  615. self.assert_(retrieved_value >= expected_value, msg)
  616. else:
  617. self.failUnlessEqual(retrieved_value, expected_value, msg)
  618. def _testUDPOption(self, level, option, values):
  619. try:
  620. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  621. self._testSetAndGetOption(sock, level, option, values)
  622. # now bind the socket i.e. cause the implementation socket to be created
  623. sock.bind( (HOST, PORT) )
  624. retrieved_option_value = sock.getsockopt(level, option)
  625. self.failUnlessEqual(retrieved_option_value, values[-1], \
  626. "Option value '(%s, %s)'='%s' did not propagate to implementation socket: got %s" % (level, option, values[-1], retrieved_option_value) )
  627. self._testSetAndGetOption(sock, level, option, values)
  628. finally:
  629. sock.close()
  630. def _testTCPClientOption(self, level, option, values):
  631. sock = None
  632. try:
  633. # First listen on a server socket, so that the connection won't be refused.
  634. server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  635. server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  636. server_sock.bind( (HOST, PORT) )
  637. server_sock.listen(50)
  638. # Now do the tests
  639. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  640. self._testSetAndGetOption(sock, level, option, values)
  641. # now connect the socket i.e. cause the implementation socket to be created
  642. # First bind, so that the SO_REUSEADDR setting propagates
  643. sock.bind( (HOST, PORT+1) )
  644. sock.connect( (HOST, PORT) )
  645. retrieved_option_value = sock.getsockopt(level, option)
  646. msg = "Option value '%s'='%s' did not propagate to implementation socket: got %s" % (option, values[-1], retrieved_option_value)
  647. if option in (socket.SO_RCVBUF, socket.SO_SNDBUF):
  648. # NOTE: there's no guarantee that bufsize will be the
  649. # exact setsockopt value, particularly after
  650. # establishing a connection. seems it will be *at least*
  651. # the values we test (which are rather small) on
  652. # BSDs.
  653. self.assert_(retrieved_option_value >= values[-1], msg)
  654. else:
  655. self.failUnlessEqual(retrieved_option_value, values[-1], msg)
  656. self._testSetAndGetOption(sock, level, option, values)
  657. finally:
  658. server_sock.close()
  659. if sock:
  660. sock.close()
  661. def _testTCPClientInheritedOption(self, level, option, values):
  662. cli_sock = accepted_sock = None
  663. try:
  664. server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  665. server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  666. self._testSetAndGetOption(server_sock, level, option, values)
  667. # now bind and listen on the socket i.e. cause the implementation socket to be created
  668. server_sock.bind( (HOST, PORT) )
  669. server_sock.listen(50)
  670. # Now create client socket to connect to server
  671. cli_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  672. cli_sock.connect( (HOST, PORT) )
  673. accepted_sock = server_sock.accept()[0]
  674. retrieved_option_value = accepted_sock.getsockopt(level, option)
  675. msg = "Option value '(%s,%s)'='%s' did not propagate to accepted socket: got %s" % (level, option, values[-1], retrieved_option_value)
  676. if option == socket.SO_RCVBUF:
  677. # NOTE: see similar bsd/solaris workaround above
  678. self.assert_(retrieved_option_value >= values[-1], msg)
  679. else:
  680. self.failUnlessEqual(retrieved_option_value, values[-1], msg)
  681. self._testSetAndGetOption(accepted_sock, level, option, values)
  682. finally:
  683. server_sock.close()
  684. if cli_sock:
  685. cli_sock.close()
  686. if accepted_sock:
  687. accepted_sock.close()
  688. def _testTCPServerOption(self, level, option, values):
  689. try:
  690. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  691. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  692. self._testSetAndGetOption(sock, level, option, values)
  693. # now bind and listen on the socket i.e. cause the implementation socket to be created
  694. sock.bind( (HOST, PORT) )
  695. sock.listen(50)
  696. retrieved_option_value = sock.getsockopt(level, option)
  697. msg = "Option value '(%s,%s)'='%s' did not propagate to implementation socket. Got %s" % (level, option, values[-1], retrieved_option_value)
  698. if option == socket.SO_RCVBUF:
  699. # NOTE: see similar bsd/solaris workaround above
  700. self.assert_(retrieved_option_value >= values[-1], msg)
  701. else:
  702. self.failUnlessEqual(retrieved_option_value, values[-1], msg)
  703. self._testSetAndGetOption(sock, level, option, values)
  704. finally:
  705. sock.close()
  706. def _testOption(self, level, option, values):
  707. for flag, func in [
  708. (self.test_udp, self._testUDPOption),
  709. (self.test_tcp_client, self._testTCPClientOption),
  710. (self.test_tcp_server, self._testTCPServerOption),
  711. ]:
  712. if flag:
  713. func(level, option, values)
  714. else:
  715. try:
  716. func(level, option, values)
  717. except socket.error, se:
  718. self.failUnlessEqual(se[0], errno.ENOPROTOOPT, "Wrong errno from unsupported option exception: %d" % se[0])
  719. except Exception, x:
  720. self.fail("Wrong exception raised from unsupported option: %s" % str(x))
  721. else:
  722. self.fail("Setting unsupported option should have raised an exception")
  723. def _testInheritedOption(self, level, option, values):
  724. try:
  725. self._testTCPClientInheritedOption(level, option, values)
  726. except Exception, x:
  727. self.fail("Inherited option should not have raised exception: %s" % str(x))
  728. class TestSupportedOptions(TestSocketOptions):
  729. def testSO_BROADCAST(self):
  730. self.test_udp = 1
  731. self._testOption(socket.SOL_SOCKET, socket.SO_BROADCAST, [0, 1])
  732. def testSO_KEEPALIVE(self):
  733. self.test_tcp_client = 1
  734. self.test_tcp_server = 1
  735. self._testOption(socket.SOL_SOCKET, socket.SO_KEEPALIVE, [0, 1])
  736. self._testInheritedOption(socket.SOL_SOCKET, socket.SO_KEEPALIVE, [0, 1])
  737. def testSO_LINGER(self):
  738. self.test_tcp_client = 1
  739. self.test_tcp_server = 1
  740. off = struct.pack('ii', 0, 0)
  741. on_2_seconds = struct.pack('ii', 1, 2)
  742. self._testOption(socket.SOL_SOCKET, socket.SO_LINGER, [off, on_2_seconds])
  743. self._testInheritedOption(socket.SOL_SOCKET, socket.SO_LINGER, [off, on_2_seconds])
  744. def testSO_OOBINLINE(self):
  745. self.test_tcp_client = 1
  746. self.test_tcp_server = 1
  747. self._testOption(socket.SOL_SOCKET, socket.SO_OOBINLINE, [0, 1])
  748. self._testInheritedOption(socket.SOL_SOCKET, socket.SO_OOBINLINE, [0, 1])
  749. def testSO_RCVBUF(self):
  750. self.test_udp = 1
  751. self.test_tcp_client = 1
  752. self.test_tcp_server = 1
  753. self._testOption(socket.SOL_SOCKET, socket.SO_RCVBUF, [1024, 4096, 16384])
  754. self._testInheritedOption(socket.SOL_SOCKET, socket.SO_RCVBUF, [1024, 4096, 16384])
  755. def testSO_REUSEADDR(self):
  756. self.test_udp = 1
  757. self.test_tcp_client = 1
  758. self.test_tcp_server = 1
  759. self._testOption(socket.SOL_SOCKET, socket.SO_REUSEADDR, [0, 1])
  760. self._testInheritedOption(socket.SOL_SOCKET, socket.SO_REUSEADDR, [0, 1])
  761. def testSO_SNDBUF(self):
  762. self.test_udp = 1
  763. self.test_tcp_client = 1
  764. self.test_tcp_server = 1
  765. self._testOption(socket.SOL_SOCKET, socket.SO_SNDBUF, [1024, 4096, 16384])
  766. self._testInheritedOption(socket.SOL_SOCKET, socket.SO_SNDBUF, [1024, 4096, 16384])
  767. def testSO_TIMEOUT(self):
  768. self.test_udp = 1
  769. self.test_tcp_client = 1
  770. self.test_tcp_server = 1
  771. self._testOption(socket.SOL_SOCKET, socket.SO_TIMEOUT, [0, 1, 1000])
  772. # We don't test inheritance here because both server and client sockets have SO_TIMEOUT
  773. # but it doesn't inherit.
  774. def testTCP_NODELAY(self):
  775. self.test_tcp_client = 1
  776. self.test_tcp_server = 1
  777. self._testOption(socket.IPPROTO_TCP, socket.TCP_NODELAY, [0, 1])
  778. self._testInheritedOption(socket.IPPROTO_TCP, socket.TCP_NODELAY, [0, 1])
  779. class TestPseudoOptions(unittest.TestCase):
  780. def testSO_ACCEPTCONN(self):
  781. for socket_type, listen, expected_result in [
  782. (socket.SOCK_STREAM, 0, 0),
  783. (socket.SOCK_STREAM, 1, 1),
  784. (socket.SOCK_DGRAM, 0, Exception),
  785. ]:
  786. s = socket.socket(socket.AF_INET, socket_type)
  787. if listen:
  788. s.listen(1)
  789. try:
  790. result = s.getsockopt(socket.SOL_SOCKET, socket.SO_ACCEPTCONN)
  791. if expected_result is not Exception:
  792. self.failUnlessEqual(result, expected_result)
  793. except socket.error, se:
  794. if expected_result is Exception:
  795. if se[0] != errno.ENOPROTOOPT:
  796. self.fail("getsockopt(SO_ACCEPTCONN) on wrong socket type raised wrong exception: %s" % str(se))
  797. else:
  798. self.fail("getsocket(SO_ACCEPTCONN) on valid socket type should not have raised exception: %s" % (str(se)))
  799. def testSO_ERROR(self):
  800. for socket_type in [socket.SOCK_STREAM, socket.SOCK_DGRAM]:
  801. s = socket.socket(socket.AF_INET, socket_type)
  802. self.failUnlessEqual(s.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR), 0)
  803. try:
  804. # Now cause an error
  805. s.connect(("localhost", 100000))
  806. self.fail("Operation '%s' that should have failed to generate SO_ERROR did not" % operation)
  807. except socket.error, se:
  808. so_error = s.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
  809. self.failUnlessEqual(so_error, se[0])
  810. # Now retrieve the option again - it should be zero
  811. self.failUnlessEqual(s.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR), 0)
  812. def testSO_TYPE(self):
  813. for socket_type in [socket.SOCK_STREAM, socket.SOCK_DGRAM]:
  814. s = socket.socket(socket.AF_INET, socket_type)
  815. self.failUnlessEqual(s.getsockopt(socket.SOL_SOCKET, socket.SO_TYPE), socket_type)
  816. class TestUnsupportedOptions(TestSocketOptions):
  817. def testSO_DEBUG(self):
  818. self.failUnless(hasattr(socket, 'SO_DEBUG'))
  819. def testSO_DONTROUTE(self):
  820. self.failUnless(hasattr(socket, 'SO_DONTROUTE'))
  821. def testSO_EXCLUSIVEADDRUSE(self):
  822. # this is an MS specific option that will not be appearing on java
  823. # http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6421091
  824. # http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6402335
  825. self.failUnless(hasattr(socket, 'SO_EXCLUSIVEADDRUSE'))
  826. def testSO_RCVLOWAT(self):
  827. self.failUnless(hasattr(socket, 'SO_RCVLOWAT'))
  828. def testSO_RCVTIMEO(self):
  829. self.failUnless(hasattr(socket, 'SO_RCVTIMEO'))
  830. def testSO_REUSEPORT(self):
  831. # not yet supported on java
  832. # http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6432031
  833. self.failUnless(hasattr(socket, 'SO_REUSEPORT'))
  834. def testSO_SNDLOWAT(self):
  835. self.failUnless(hasattr(socket, 'SO_SNDLOWAT'))
  836. def testSO_SNDTIMEO(self):
  837. self.failUnless(hasattr(socket, 'SO_SNDTIMEO'))
  838. def testSO_USELOOPBACK(self):
  839. self.failUnless(hasattr(socket, 'SO_USELOOPBACK'))
  840. class BasicTCPTest(SocketConnectedTest):
  841. def __init__(self, methodName='runTest'):
  842. SocketConnectedTest.__init__(self, methodName=methodName)
  843. def testRecv(self):
  844. # Testing large receive over TCP
  845. msg = self.cli_conn.recv(1024)
  846. self.assertEqual(msg, MSG)
  847. def _testRecv(self):
  848. self.serv_conn.send(MSG)
  849. def testRecvTimeoutMode(self):
  850. # Do this test in timeout mode, because the code path is different
  851. self.cli_conn.settimeout(10)
  852. msg = self.cli_conn.recv(1024)
  853. self.assertEqual(msg, MSG)
  854. def _testRecvTimeoutMode(self):
  855. self.serv_conn.settimeout(10)
  856. self.serv_conn.send(MSG)
  857. def testOverFlowRecv(self):
  858. # Testing receive in chunks over TCP
  859. seg1 = self.cli_conn.recv(len(MSG) - 3)
  860. seg2 = self.cli_conn.recv(1024)
  861. msg = seg1 + seg2
  862. self.assertEqual(msg, MSG)
  863. def _testOverFlowRecv(self):
  864. self.serv_conn.send(MSG)
  865. def testRecvFrom(self):
  866. # Testing large recvfrom() over TCP
  867. msg, addr = self.cli_conn.recvfrom(1024)
  868. self.assertEqual(msg, MSG)
  869. def _testRecvFrom(self):
  870. self.serv_conn.send(MSG)
  871. def testOverFlowRecvFrom(self):
  872. # Testing recvfrom() in chunks over TCP
  873. seg1, addr = self.cli_conn.recvfrom(len(MSG)-3)
  874. seg2, addr = self.cli_conn.recvfrom(1024)
  875. msg = seg1 + seg2
  876. self.assertEqual(msg, MSG)
  877. def _testOverFlowRecvFrom(self):
  878. self.serv_conn.send(MSG)
  879. def testSendAll(self):
  880. # Testing sendall() with a 2048 byte string over TCP
  881. msg = ''
  882. while 1:
  883. read = self.cli_conn.recv(1024)
  884. if not read:
  885. break
  886. msg += read
  887. self.assertEqual(msg, 'f' * 2048)
  888. def _testSendAll(self):
  889. big_chunk = 'f' * 2048
  890. self.serv_conn.sendall(big_chunk)
  891. def testFromFd(self):
  892. # Testing fromfd()
  893. if not hasattr(socket, "fromfd"):
  894. return # On Windows, this doesn't exist
  895. fd = self.cli_conn.fileno()
  896. sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
  897. msg = sock.recv(1024)
  898. self.assertEqual(msg, MSG)
  899. def _testFromFd(self):
  900. self.serv_conn.send(MSG)
  901. def testShutdown(self):
  902. # Testing shutdown()
  903. msg = self.cli_conn.recv(1024)
  904. self.assertEqual(msg, MSG)
  905. def _testShutdown(self):
  906. self.serv_conn.send(MSG)
  907. self.serv_conn.shutdown(2)
  908. def testSendAfterRemoteClose(self):
  909. self.cli_conn.close()
  910. def _testSendAfterRemoteClose(self):
  911. for x in range(5):
  912. try:
  913. self.serv_conn.send("spam")
  914. except socket.error, se:
  915. self.failUnlessEqual(se[0], errno.ECONNRESET)
  916. return
  917. except Exception, x:
  918. self.fail("Sending on remotely closed socket raised wrong exception: %s" % x)
  919. time.sleep(0.5)
  920. self.fail("Sending on remotely closed socket should have raised exception")
  921. def testDup(self):
  922. msg = self.cli_conn.recv(len(MSG))
  923. self.assertEqual(msg, MSG)
  924. dup_conn = self.cli_conn.dup()
  925. msg = dup_conn.recv(len('and ' + MSG))
  926. self.assertEqual(msg, 'and ' + MSG)
  927. def _testDup(self):
  928. self.serv_conn.send(MSG)
  929. self.serv_conn.send('and ' + MSG)
  930. class UDPBindTest(unittest.TestCase):
  931. HOST = HOST
  932. PORT = PORT
  933. def setUp(self):
  934. self.sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
  935. def testBindSpecific(self):
  936. self.sock.bind( (self.HOST, self.PORT) ) # Use a specific port
  937. actual_port = self.sock.getsockname()[1]
  938. self.failUnless(actual_port == self.PORT,
  939. "Binding to specific port number should have returned same number: %d != %d" % (actual_port, self.PORT))
  940. def testBindEphemeral(self):
  941. self.sock.bind( (self.HOST, 0) ) # let system choose a free port
  942. self.failUnless(self.sock.getsockname()[1] != 0, "Binding to port zero should have allocated an ephemeral port number")
  943. def testShutdown(self):
  944. self.sock.bind( (self.HOST, self.PORT) )
  945. self.sock.shutdown(socket.SHUT_RDWR)
  946. def tearDown(self):
  947. self.sock.close()
  948. class BasicUDPTest(ThreadedUDPSocketTest):
  949. def __init__(self, methodName='runTest'):
  950. ThreadedUDPSocketTest.__init__(self, methodName=methodName)
  951. def testSendtoAndRecv(self):
  952. # Testing sendto() and recv() over UDP
  953. msg = self.serv.recv(len(MSG))
  954. self.assertEqual(msg, MSG)
  955. def _testSendtoAndRecv(self):
  956. self.cli.sendto(MSG, 0, (self.HOST, self.PORT))
  957. def testSendtoAndRecvTimeoutMode(self):
  958. # Need to test again in timeout mode, which follows
  959. # a different code path
  960. self.serv.settimeout(10)
  961. msg = self.serv.recv(len(MSG))
  962. self.assertEqual(msg, MSG)
  963. def _testSendtoAndRecvTimeoutMode(self):
  964. self.cli.settimeout(10)
  965. self.cli.sendto(MSG, 0, (self.HOST, self.PORT))
  966. def testSendAndRecv(self):
  967. # Testing send() and recv() over connect'ed UDP
  968. msg = self.serv.recv(len(MSG))
  969. self.assertEqual(msg, MSG)
  970. def _testSendAndRecv(self):
  971. self.cli.connect( (self.HOST, self.PORT) )
  972. self.cli.send(MSG, 0)
  973. def testSendAndRecvTimeoutMode(self):
  974. # Need to test again in timeout mode, which follows
  975. # a different code path
  976. self.serv.settimeout(10)
  977. # Testing send() and recv() over connect'ed UDP
  978. msg = self.serv.recv(len(MSG))
  979. self.assertEqual(msg, MSG)
  980. def _testSendAndRecvTimeoutMode(self):
  981. self.cli.connect( (self.HOST, self.PORT) )
  982. self.cli.settimeout(10)
  983. self.cli.send(MSG, 0)
  984. def testRecvFrom(self):
  985. # Testing recvfrom() over UDP
  986. msg, addr = self.serv.recvfrom(len(MSG))
  987. self.assertEqual(msg, MSG)
  988. def _testRecvFrom(self):
  989. self.cli.sendto(MSG, 0, (self.HOST, self.PORT))
  990. def testRecvFromTimeoutMode(self):
  991. # Need to test again in timeout mode, which follows
  992. # a different code path
  993. self.serv.settimeout(10)
  994. msg, addr = self.serv.recvfrom(len(MSG))
  995. self.assertEqual(msg, MSG)
  996. def _testRecvFromTimeoutMode(self):
  997. self.cli.settimeout(10)
  998. self.cli.sendto(MSG, 0, (self.HOST, self.PORT))
  999. def testSendtoEightBitSafe(self):
  1000. # This test is necessary because java only supports signed bytes
  1001. msg = self.serv.recv(len(EIGHT_BIT_MSG))
  1002. self.assertEqual(msg, EIGHT_BIT_MSG)
  1003. def _testSendtoEightBitSafe(self):
  1004. self.cli.sendto(EIGHT_BIT_MSG, 0, (self.HOST, self.PORT))
  1005. def testSendtoEightBitSafeTimeoutMode(self):
  1006. # Need to test again in timeout mode, which follows
  1007. # a different code path
  1008. self.serv.settimeout(10)
  1009. msg = self.serv.recv(len(EIGHT_BIT_MSG))
  1010. self.assertEqual(msg, EIGHT_BIT_MSG)
  1011. def _testSendtoEightBitSafeTimeoutMode(self):
  1012. self.cli.settimeout(10)
  1013. self.cli.sendto(EIGHT_BIT_MSG, 0, (self.HOST, self.PORT))
  1014. class UDPBroadcastTest(ThreadedUDPSocketTest):
  1015. def setUp(self):
  1016. self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  1017. self.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  1018. def testBroadcast(self):
  1019. self.serv.bind( ("", self.PORT) )
  1020. msg = self.serv.recv(len(EIGHT_BIT_MSG))
  1021. self.assertEqual(msg, EIGHT_BIT_MSG)
  1022. def _testBroadcast(self):
  1023. self.cli.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
  1024. self.cli.sendto(EIGHT_BIT_MSG, ("<broadcast>", self.PORT) )
  1025. class BasicSocketPairTest(SocketPairTest):
  1026. def __init__(self, methodName='runTest'):
  1027. SocketPairTest.__init__(self, methodName=methodName)
  1028. def testRecv(self):
  1029. msg = self.serv.recv(1024)
  1030. self.assertEqual(msg, MSG)
  1031. def _testRecv(self):
  1032. self.cli.send(MSG)
  1033. def testSend(self):
  1034. self.serv.send(MSG)
  1035. def _testSend(self):
  1036. msg = self.cli.recv(1024)
  1037. self.assertEqual(msg, MSG)
  1038. class NonBlockingTCPServerTests(SocketTCPTest):
  1039. def testSetBlocking(self):
  1040. # Testing whether set blocking works
  1041. self.serv.setblocking(0)
  1042. start = time.time()
  1043. try:
  1044. self.serv.accept()
  1045. except socket.error:
  1046. pass
  1047. end = time.time()
  1048. self.assert_((end - start) < 1.0, "Error setting non-blocking mode.")
  1049. def testGetBlocking(self):
  1050. # Testing whether set blocking works
  1051. self.serv.setblocking(0)
  1052. self.failUnless(not self.serv.getblocking(), "Getblocking return true instead of false")
  1053. self.serv.setblocking(1)
  1054. self.failUnless(self.serv.getblocking(), "Getblocking return false instead of true")
  1055. def testAcceptNoConnection(self):
  1056. # Testing non-blocking accept returns immediately when no connection
  1057. self.serv.setblocking(0)
  1058. try:
  1059. conn, addr = self.serv.accept()
  1060. except socket.error:
  1061. pass
  1062. else:
  1063. self.fail("Error trying to do non-blocking accept.")
  1064. class NonBlockingTCPTests(ThreadedTCPSocketTest):
  1065. def __init__(self, methodName='runTest'):
  1066. ThreadedTCPSocketTest.__init__(self, methodName=methodName)
  1067. def testAcceptConnection(self):
  1068. # Testing non-blocking accept works when connection present
  1069. self.serv.setblocking(0)
  1070. read, write, err = select.select([self.serv], [], [])
  1071. if self.serv in read:
  1072. conn, addr = self.serv.accept()
  1073. else:
  1074. self.fail("Error trying to do accept after select: server socket was not in 'read'able list")
  1075. def _testAcceptConnection(self):
  1076. # Make a connection to the server
  1077. self.cli.connect((self.HOST, self.PORT))
  1078. #
  1079. # AMAK: 20070311
  1080. # Introduced a new test for non-blocking connect
  1081. # Renamed old testConnect to testBlockingConnect
  1082. #
  1083. def testBlockingConnect(self):
  1084. # Testing blocking connect
  1085. conn, addr = self.serv.accept()
  1086. def _testBlockingConnect(self):
  1087. # Testing blocking connect
  1088. self.cli.settimeout(10)
  1089. self.cli.connect((self.HOST, self.PORT))
  1090. def testNonBlockingConnect(self):
  1091. # Testing non-blocking connect
  1092. conn, addr = self.serv.accept()
  1093. def _testNonBlockingConnect(self):
  1094. # Testing non-blocking connect
  1095. self.cli.setblocking(0)
  1096. result = self.cli.connect_ex((self.HOST, self.PORT))
  1097. rfds, wfds, xfds = select.select([], [self.cli], [])
  1098. self.failUnless(self.cli in wfds)
  1099. try:
  1100. self.cli.send(MSG)
  1101. except socket.error:
  1102. self.fail("Sending on connected socket should not have raised socket.error")
  1103. #
  1104. # AMAK: 20070518
  1105. # Introduced a new test for connect with bind to specific local address
  1106. #
  1107. def testConnectWithLocalBind(self):
  1108. # Test blocking connect
  1109. conn, addr = self.serv.accept()
  1110. def _testConnectWithLocalBind(self):
  1111. # Testing blocking connect with local bind
  1112. cli_port = self.PORT - 1
  1113. while True:
  1114. # Keep trying until a local port is available
  1115. self.cli.settimeout(1)
  1116. self.cli.bind( (self.HOST, cli_port) )
  1117. try:
  1118. self.cli.connect((self.HOST, self.PORT))
  1119. break
  1120. except socket.error, se:
  1121. # cli_port is in use (maybe in TIME_WAIT state from a
  1122. # previous test run). reset the client socket and try
  1123. # again
  1124. self.failUnlessEqual(se[0], errno.EADDRINUSE)
  1125. try:
  1126. self.cli.close()
  1127. except socket.error:
  1128. pass
  1129. self.clientSetUp()
  1130. cli_port -= 1
  1131. bound_host, bound_port = self.cli.getsockname()
  1132. self.failUnlessEqual(bound_port, cli_port)
  1133. def testRecvData(self):
  1134. # Testing non-blocking recv
  1135. conn, addr = self.serv.accept()
  1136. conn.setblocking(0)
  1137. rfds, wfds, xfds = select.select([conn], [], [])
  1138. if conn in rfds:
  1139. msg = conn.recv(len(MSG))
  1140. self.assertEqual(msg, MSG)
  1141. else:
  1142. self.fail("Non-blocking socket with data should been in read list.")
  1143. def _testRecvData(self):
  1144. self.cli.connect((self.HOST, self.PORT))
  1145. self.cli.send(MSG)
  1146. def testRecvNoData(self):
  1147. # Testing non-blocking recv
  1148. conn, addr = self.serv.accept()
  1149. conn.setblocking(0)
  1150. try:
  1151. msg = conn.recv(len(MSG))
  1152. except socket.error:
  1153. pass
  1154. else:
  1155. self.fail("Non-blocking recv of no data should have raised socket.error.")
  1156. def _testRecvNoData(self):
  1157. self.cli.connect((self.HOST, self.PORT))
  1158. time.sleep(0.1)
  1159. class NonBlockingUDPTests(ThreadedUDPSocketTest): pass
  1160. #
  1161. # TODO: Write some non-blocking UDP tests
  1162. #
  1163. class TCPFileObjectClassOpenCloseTests(SocketConnectedTest):
  1164. def testCloseFileDoesNotCloseSocket(self):
  1165. # This test is necessary on java/jython
  1166. msg = self.cli_conn.recv(1024)
  1167. self.assertEqual(msg, MSG)
  1168. def _testCloseFileDoesNotCloseSocket(self):
  1169. self.cli_file = self.serv_conn.makefile('wb')
  1170. self.cli_file.close()
  1171. try:
  1172. self.serv_conn.send(MSG)
  1173. except Exception, x:
  1174. self.fail("Closing file wrapper appears to have closed underlying socket: %s" % str(x))
  1175. def testCloseSocketDoesNotCloseFile(self):
  1176. msg = self.cli_conn.recv(1024)
  1177. self.assertEqual(msg, MSG)
  1178. def _testCloseSocketDoesNotCloseFile(self):
  1179. self.cli_file = self.serv_conn.makefile('wb')
  1180. self.serv_conn.close()
  1181. try:
  1182. self.cli_file.write(MSG)
  1183. self.cli_file.flush()
  1184. except Exception, x:
  1185. self.fail("Closing socket appears to have closed file wrapper: %s" % str(x))
  1186. class UDPFileObjectClassOpenCloseTests(ThreadedUDPSocketTest):
  1187. def testCloseFileDoesNotCloseSocket(self):
  1188. # This test is necessary on java/jython
  1189. msg = self.serv.recv(1024)
  1190. self.assertEqual(msg, MSG)
  1191. def _testCloseFileDoesNotCloseSocket(self):
  1192. self.cli_file = self.cli.makefile('wb')
  1193. self.cli_file.close()
  1194. try:
  1195. self.cli.sendto(MSG, 0, (self.HOST, self.PORT))
  1196. except Exception, x:
  1197. self.fail("Closing file wrapper appears to have closed underlying socket: %s" % str(x))
  1198. def testCloseSocketDoesNotCloseFile(self):
  1199. self.serv_file = self.serv.makefile('rb')
  1200. self.serv.close()
  1201. msg = self.serv_file.readline()
  1202. self.assertEqual(msg, MSG)
  1203. def _testCloseSocketDoesNotCloseFile(self):
  1204. try:
  1205. self.cli.sendto(MSG, 0, (self.HOST, self.PORT))
  1206. except Exception, x:
  1207. self.fail("Closing file wrapper appears to have closed underlying socket: %s" % str(x))
  1208. class FileAndDupOpenCloseTests(SocketConnectedTest):
  1209. def testCloseDoesNotCloseOthers(self):
  1210. msg = self.cli_conn.recv(len(MSG))
  1211. self.assertEqual(msg, MSG)
  1212. msg = self.cli_conn.recv(len('and ' + MSG))
  1213. self.assertEqual(msg, 'and ' + MSG)
  1214. def _testCloseDoesNotCloseOthers(self):
  1215. self.dup_conn1 = self.serv_conn.dup()
  1216. self.dup_conn2 = self.serv_conn.dup()
  1217. self.cli_file = self.serv_conn.makefile('wb')
  1218. self.serv_conn.close()
  1219. self.dup_conn1.close()
  1220. try:
  1221. self.serv_conn.send(MSG)
  1222. except socket.error, se:
  1223. self.failUnlessEqual(se[0], errno.EBADF)
  1224. else:
  1225. self.fail("Original socket did not close")
  1226. try:
  1227. self.dup_conn1.send(MSG)
  1228. except socket.error, se:
  1229. self.failUnlessEqual(se[0], errno.EBADF)
  1230. else:
  1231. self.fail("Duplicate socket 1 did not close")
  1232. self.dup_conn2.send(MSG)
  1233. self.dup_conn2.close()
  1234. try:
  1235. self.cli_file.write('and ' + MSG)
  1236. except Exception, x:
  1237. self.fail("Closing others appears to have closed the socket file: %s" % str(x))
  1238. self.cli_file.close()
  1239. class FileObjectClassTestCase(SocketConnectedTest):
  1240. bufsize = -1 # Use default buffer size
  1241. def __init__(self, methodName='runTest'):
  1242. SocketConnectedTest.__init__(self, methodName=methodName)
  1243. def setUp(self):
  1244. SocketConnectedTest.setUp(self)
  1245. self.serv_file = self.cli_conn.makefile('rb', self.bufsize)
  1246. def tearDown(self):
  1247. self.serv_file.close()
  1248. self.assert_(self.serv_file.closed)
  1249. self.serv_file = None
  1250. SocketConnectedTest.tearDown(self)
  1251. def clientSetUp(self):
  1252. SocketConnectedTest.clientSetUp(self)
  1253. self.cli_file = self.serv_conn.makefile('wb')
  1254. def clientTearDown(self):
  1255. self.cli_file.close()
  1256. self.assert_(self.cli_file.closed)
  1257. self.cli_file = None
  1258. SocketConnectedTest.clientTearDown(self)
  1259. def testSmallRead(self):
  1260. # Performing small file read test
  1261. first_seg = self.serv_file.read(len(MSG)-3)
  1262. second_seg = self.serv_file.read(3)
  1263. msg = first_seg + second_seg
  1264. self.assertEqual(msg, MSG)
  1265. def _testSmallRead(self):
  1266. self.cli_file.write(MSG)
  1267. self.cli_file.flush()
  1268. def testFullRead(self):
  1269. # read until EOF
  1270. msg = self.serv_file.read()
  1271. self.assertEqual(msg, MSG)
  1272. def _testFullRead(self):
  1273. self.cli_file.write(MSG)
  1274. self.cli_file.flush()
  1275. def testUnbufferedRead(self):
  1276. # Performing unbuffered file read test
  1277. buf = ''
  1278. while 1:
  1279. char = self.serv_file.read(1)
  1280. if not char:
  1281. break
  1282. buf += char
  1283. self.assertEqual(buf, MSG)
  1284. def _testUnbufferedRead(self):
  1285. self.cli_file.write(MSG)
  1286. self.cli_file.flush()
  1287. def testReadline(self):
  1288. # Performing file readline test
  1289. line = self.serv_file.readline()
  1290. self.assertEqual(line, MSG)
  1291. def _testReadline(self):
  1292. self.cli_file.write(MSG)
  1293. self.cli_file.flush()
  1294. def testClosedAttr(self):
  1295. self.assert_(not self.serv_file.closed)
  1296. def _testClosedAttr(self):
  1297. self.assert_(not self.cli_file.closed)
  1298. class PrivateFileObjectTestCase(unittest.TestCase):
  1299. """Test usage of socket._fileobject with an arbitrary socket-like
  1300. object.
  1301. E.g. urllib2 wraps an httplib.HTTPResponse object with _fileobject.
  1302. """
  1303. def setUp(self):
  1304. self.socket_like = StringIO()
  1305. self.socket_like.recv = self.socket_like.read
  1306. self.socket_like.sendall = self.socket_like.write
  1307. def testPrivateFileObject(self):
  1308. fileobject = socket._fileobject(self.socket_like, 'rb')
  1309. fileobject.write('hello jython')
  1310. fileobject.flush()
  1311. self.socket_like.seek(0)
  1312. self.assertEqual(fileobject.read(), 'hello jython')
  1313. class UnbufferedFileObjectClassTestCase(FileObjectClassTestCase):
  1314. """Repeat the tests from FileObjectClassTestCase with bufsize==0.
  1315. In this case (and in this case only), it should be possible to
  1316. create a file object, read a line from it, create another file
  1317. object, read another line from it, without loss of data in the
  1318. first file object's buffer. Note that httplib relies on this
  1319. when reading multiple requests from the same socket."""
  1320. bufsize = 0 # Use unbuffered mode
  1321. def testUnbufferedReadline(self):
  1322. # Read a line, create a new file object, read another line with it
  1323. line = self.serv_file.readline() # first line
  1324. self.assertEqual(line, "A. " + MSG) # first line
  1325. self.serv_file = self.cli_conn.makefile('rb', 0)
  1326. line = self.serv_file.readline() # second line
  1327. self.assertEqual(line, "B. " + MSG) # second line
  1328. def _testUnbufferedReadline(self):
  1329. self.cli_file.write("A. " + MSG)
  1330. self.cli_file.write("B. " + MSG)
  1331. self.cli_file.flush()
  1332. class LineBufferedFileObjectClassTestCase(FileObjectClassTestCase):
  1333. bufsize = 1 # Default-buffered for reading; line-buffered for writing
  1334. class SmallBufferedFileObjectClassTestCase(FileObjectClassTestCase):
  1335. bufsize = 2 # Exercise the buffering code
  1336. class TCPServerTimeoutTest(SocketTCPTest):
  1337. def testAcceptTimeout(self):
  1338. def raise_timeout(*args, **kwargs):
  1339. self.serv.settimeout(1.0)
  1340. self.serv.accept()
  1341. self.failUnlessRaises(socket.timeout, raise_timeout,
  1342. "TCP socket accept failed to generate a timeout exception (TCP)")
  1343. def testTimeoutZero(self):
  1344. ok = False
  1345. try:
  1346. self.serv.settimeout(0.0)
  1347. foo = self.serv.accept()
  1348. except socket.timeout:
  1349. self.fail("caught timeout instead of error (TCP)")
  1350. except socket.error:
  1351. ok = True
  1352. except Exception, x:
  1353. self.fail("caught unexpected exception (TCP): %s" % str(x))
  1354. if not ok:
  1355. self.fail("accept() returned success when we did not expect it")
  1356. class TCPClientTimeoutTest(SocketTCPTest):
  1357. def testConnectTimeout(self):
  1358. cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  1359. cli.settimeout(0.1)
  1360. host = '192.168.192.168'
  1361. try:
  1362. cli.connect((host, 5000))
  1363. except socket.timeout, st:
  1364. pass
  1365. except Exception, x:
  1366. self.fail("Client socket timeout should have raised socket.timeout, not %s" % str(x))
  1367. else:
  1368. self.fail('''Client socket timeout should have raised
  1369. socket.timeout. This tries to connect to %s in the assumption that it isn't
  1370. used, but if it is on your network this failure is bogus.''' % host)
  1371. def testConnectDefaultTimeout(self):
  1372. _saved_timeout = socket.getdefaulttimeout()
  1373. socket.setdefaulttimeout(0.1)
  1374. cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  1375. host = '192.168.192.168'
  1376. try:
  1377. cli.connect((host, 5000))
  1378. except socket.timeout, st:
  1379. pass
  1380. except Exception, x:
  1381. self.fail("Client socket timeout should have raised socket.timeout, not %s" % str(x))
  1382. else:
  1383. self.fail('''Client socket timeout should have raised
  1384. socket.timeout. This tries to connect to %s in the assumption that it isn't
  1385. used, but if it is on your network this failure is bogus.''' % host)
  1386. socket.setdefaulttimeout(_saved_timeout)
  1387. def testRecvTimeout(self):
  1388. def raise_timeout(*args, **kwargs):
  1389. cli_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  1390. cli_sock.connect( (HOST, PORT) )
  1391. cli_sock.settimeout(1)
  1392. cli_sock.recv(1024)
  1393. self.failUnlessRaises(socket.timeout, raise_timeout,
  1394. "TCP socket recv failed to generate a timeout exception (TCP)")
  1395. # Disable this test, but leave it present for documentation purposes
  1396. # socket timeouts only work for read and accept, not for write
  1397. # http://java.sun.com/j2se/1.4.2/docs/api/java/net/SocketTimeoutException.html
  1398. def estSendTimeout(self):
  1399. def raise_timeout(*args, **kwargs):
  1400. cli_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  1401. cli_sock.connect( (HOST, PORT) )
  1402. # First fill the socket
  1403. cli_sock.settimeout(1)
  1404. sent = 0
  1405. while True:
  1406. bytes_sent = cli_sock.send(MSG)
  1407. sent += bytes_sent
  1408. self.failUnlessRaises(socket.timeout, raise_timeout,
  1409. "TCP socket send failed to generate a timeout exception (TCP)")
  1410. def testSwitchModes(self):
  1411. cli_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  1412. cli_sock.connect( (HOST, PORT) )
  1413. # set non-blocking mode
  1414. cli_sock.setblocking(0)
  1415. # then set timeout mode
  1416. cli_sock.settimeout(1)
  1417. try:
  1418. cli_sock.send(MSG)
  1419. except Exception, x:
  1420. self.fail("Switching mode from non-blocking to timeout raised exception: %s" % x)
  1421. else:
  1422. pass
  1423. #
  1424. # AMAK: 20070307
  1425. # Corrected the superclass of UDPTimeoutTest
  1426. #
  1427. class UDPTimeoutTest(SocketUDPTest):
  1428. def testUDPTimeout(self):
  1429. def raise_timeout(*args, **kwargs):
  1430. self.serv.settimeout(1.0)
  1431. self.serv.recv(1024)
  1432. self.failUnlessRaises(socket.timeout, raise_timeout,
  1433. "Error generating a timeout exception (UDP)")
  1434. def testTimeoutZero(self):
  1435. ok = False
  1436. try:
  1437. self.serv.settimeout(0.0)
  1438. foo = self.serv.recv(1024)
  1439. except socket.timeout:
  1440. self.fail("caught timeout instead of error (UDP)")
  1441. except socket.error:
  1442. ok = True
  1443. except Exception, x:
  1444. self.fail("caught unexpected exception (UDP): %s" % str(x))
  1445. if not ok:
  1446. self.fail("recv() returned success when we did not expect it")
  1447. class TestGetAddrInfo(unittest.TestCase):
  1448. def testBadFamily(self):
  1449. try:
  1450. socket.getaddrinfo(HOST, PORT, 9999)
  1451. except socket.gaierror, gaix:
  1452. self.failUnlessEqual(gaix[0], errno.EIO)
  1453. except Exception, x:
  1454. self.fail("getaddrinfo with bad family raised wrong exception: %s" % x)
  1455. else:
  1456. self.fail("getaddrinfo with bad family should have raised exception")
  1457. def testBadSockType(self):
  1458. for socktype in [socket.SOCK_RAW, socket.SOCK_RDM, socket.SOCK_SEQPACKET]:
  1459. try:
  1460. socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socktype)
  1461. except socket.error, se:
  1462. self.failUnlessEqual(se[0], errno.ESOCKTNOSUPPORT)
  1463. except Exception, x:
  1464. self.fail("getaddrinfo with bad socktype raised wrong exception: %s" % x)
  1465. else:
  1466. self.fail("getaddrinfo with bad socktype should have raised exception")
  1467. def testBadSockTypeProtoCombination(self):
  1468. for socktype, proto in [
  1469. (socket.SOCK_STREAM, socket.IPPROTO_UDP),
  1470. (socket.SOCK_STREAM, socket.IPPROTO_ICMP),
  1471. (socket.SOCK_DGRAM, socket.IPPROTO_TCP),
  1472. (socket.SOCK_DGRAM, socket.IPPROTO_FRAGMENT),
  1473. ]:
  1474. try:
  1475. results = socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socktype, proto)
  1476. self.failUnless(len(results) == 0, "getaddrinfo with bad socktype/proto combo should not have returned results")
  1477. except Exception, x:
  1478. self.fail("getaddrinfo with bad socktype/proto combo should not have raised exception")
  1479. def testNoSockTypeWithProto(self):
  1480. for expect_results, proto in [
  1481. (True, socket.IPPROTO_UDP),
  1482. (False, socket.IPPROTO_ICMP),
  1483. (True, socket.IPPROTO_TCP),
  1484. (False, socket.IPPROTO_FRAGMENT),
  1485. ]:
  1486. try:
  1487. results = socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, 0, proto)
  1488. if expect_results:
  1489. self.failUnless(len(results) > 0, "getaddrinfo with no socktype and supported proto combo should have returned results")
  1490. else:
  1491. self.failUnless(len(results) == 0, "getaddrinfo with no socktype and unsupported proto combo should not have returned results")
  1492. except Exception, x:
  1493. self.fail("getaddrinfo with no socktype (un)supported proto combo should not have raised exception")
  1494. def testReturnsAreStrings(self):
  1495. addrinfos = socket.getaddrinfo(HOST, PORT)
  1496. for addrinfo in addrinfos:
  1497. family, socktype, proto, canonname, sockaddr = addrinfo
  1498. self.assert_(isinstance(canonname, str))
  1499. self.assert_(isinstance(sockaddr[0], str))
  1500. def testAI_PASSIVE(self):
  1501. # Disabling this test for now; it's expectations are not portable.
  1502. # Expected results are too dependent on system config to be made portable between systems.
  1503. # And the only way to determine what configuration to test is to use the
  1504. # java.net.InetAddress.getAllByName() method, which is what is used to
  1505. # implement the getaddrinfo() function. Therefore, no real point in the test.
  1506. return
  1507. IPV4_LOOPBACK = "127.0.0.1"
  1508. local_hostname = java.net.InetAddress.getLocalHost().getHostName()
  1509. local_ip_address = java.net.InetAddress.getLocalHost().getHostAddress()
  1510. for flags, host_param, expected_canonname, expected_sockaddr in [
  1511. # First passive flag
  1512. (socket.AI_PASSIVE, None, "", socket.INADDR_ANY),
  1513. (socket.AI_PASSIVE, "", "", local_ip_address),
  1514. (socket.AI_PASSIVE, "localhost", "", IPV4_LOOPBACK),
  1515. (socket.AI_PASSIVE, local_hostname, "", local_ip_address),
  1516. # Now passive flag AND canonname flag
  1517. # Commenting out all AI_CANONNAME tests, results too dependent on system config
  1518. #(socket.AI_PASSIVE|socket.AI_CANONNAME, None, "127.0.0.1", "127.0.0.1"),
  1519. #(socket.AI_PASSIVE|socket.AI_CANONNAME, "", local_hostname, local_ip_address),
  1520. # The following gives varying results across platforms and configurations: commenting out for now.
  1521. # Javadoc: http://java.sun.com/j2se/1.5.0/docs/api/java/net/InetAddress.html#getCanonicalHostName()
  1522. #(socket.AI_PASSIVE|socket.AI_CANONNAME, "localhost", local_hostname, IPV4_LOOPBACK),
  1523. #(socket.AI_PASSIVE|socket.AI_CANONNAME, local_hostname, local_hostname, local_ip_address),
  1524. ]:
  1525. addrinfos = socket.getaddrinfo(host_param, 0, socket.AF_INET, socket.SOCK_STREAM, 0, flags)
  1526. for family, socktype, proto, canonname, sockaddr in addrinfos:
  1527. self.failUnlessEqual(expected_canonname, canonname, "For hostname '%s' and flags %d, canonname '%s' != '%s'" % (host_param, flags, expected_canonname, canonname) )
  1528. self.failUnlessEqual(expected_sockaddr, sockaddr[0], "For hostname '%s' and flags %d, sockaddr '%s' != '%s'" % (host_param, flags, expected_sockaddr, sockaddr[0]) )
  1529. def testIPV4AddressesOnly(self):
  1530. socket._use_ipv4_addresses_only(True)
  1531. def doAddressTest(addrinfos):
  1532. for family, socktype, proto, canonname, sockaddr in addrinfos:
  1533. self.failIf(":" in sockaddr[0], "Incorrectly received IPv6 address '%s'" % (sockaddr[0]) )
  1534. doAddressTest(socket.getaddrinfo("localhost", 0, socket.AF_INET6, socket.SOCK_STREAM, 0, 0))
  1535. doAddressTest(socket.getaddrinfo("localhost", 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, 0))
  1536. socket._use_ipv4_addresses_only(False)
  1537. def testAddrTupleTypes(self):
  1538. ipv4_address_tuple = socket.getaddrinfo("localhost", 80, socket.AF_INET, socket.SOCK_STREAM, 0, 0)[0][4]
  1539. self.failUnlessEqual(ipv4_address_tuple[0], "127.0.0.1")
  1540. self.failUnlessEqual(ipv4_address_tuple[1], 80)
  1541. self.failUnlessRaises(IndexError, lambda: ipv4_address_tuple[2])
  1542. self.failUnlessEqual(str(ipv4_address_tuple), "('127.0.0.1', 80)")
  1543. self.failUnlessEqual(repr(ipv4_address_tuple), "('127.0.0.1', 80)")
  1544. addrinfo = socket.getaddrinfo("localhost", 80, socket.AF_INET6, socket.SOCK_STREAM, 0, 0)
  1545. if not addrinfo:
  1546. # Maybe no IPv6 configured on the test machine.
  1547. return
  1548. ipv6_address_tuple = addrinfo[0][4]
  1549. self.failUnless (ipv6_address_tuple[0] in ["::1", "0:0:0:0:0:0:0:1"])
  1550. self.failUnlessEqual(ipv6_address_tuple[1], 80)
  1551. self.failUnlessEqual(ipv6_address_tuple[2], 0)
  1552. # Can't have an expectation for scope
  1553. try:
  1554. ipv6_address_tuple[3]
  1555. except IndexError:
  1556. self.fail("Failed to retrieve third element of ipv6 4-tuple")
  1557. self.failUnlessRaises(IndexError, lambda: ipv6_address_tuple[4])
  1558. # These str/repr tests may fail on some systems: the scope element of the tuple may be non-zero
  1559. # In this case, we'll have to change the test to use .startswith() or .split() to exclude the scope element
  1560. self.failUnless(str(ipv6_address_tuple) in ["('::1', 80, 0, 0)", "('0:0:0:0:0:0:0:1', 80, 0, 0)"])
  1561. self.failUnless(repr(ipv6_address_tuple) in ["('::1', 80, 0, 0)", "('0:0:0:0:0:0:0:1', 80, 0, 0)"])
  1562. def testNonIntPort(self):
  1563. hostname = "localhost"
  1564. # Port value of None should map to 0
  1565. addrs = socket.getaddrinfo(hostname, None)
  1566. for a in addrs:
  1567. self.failUnlessEqual(a[4][1], 0, "Port value of None should have returned 0")
  1568. # Port value can be a string rep of the port number
  1569. addrs = socket.getaddrinfo(hostname, "80")
  1570. for a in addrs:
  1571. self.failUnlessEqual(a[4][1], 80, "Port value of '80' should have returned 80")
  1572. # Can also specify a service name
  1573. # This test assumes that service http will always be at port 80
  1574. addrs = socket.getaddrinfo(hostname, "http")
  1575. for a in addrs:
  1576. self.failUnlessEqual(a[4][1], 80, "Port value of 'http' should have returned 80")
  1577. # Check treatment of non-integer numeric port
  1578. try:
  1579. socket.getaddrinfo(hostname, 79.99)
  1580. except socket.error, se:
  1581. self.failUnlessEqual(se[0], "Int or String expected")
  1582. except Exception, x:
  1583. self.fail("getaddrinfo for float port number raised wrong exception: %s" % str(x))
  1584. else:
  1585. self.fail("getaddrinfo for float port number failed to raise exception")
  1586. # Check treatment of non-integer numeric port, as a string
  1587. # The result is that it should fail in the same way as a non-existent service
  1588. try:
  1589. socket.getaddrinfo(hostname, "79.99")
  1590. except socket.gaierror, g:
  1591. self.failUnlessEqual(g[0], socket.EAI_SERVICE)
  1592. except Exception, x:
  1593. self.fail("getaddrinfo for non-integer numeric port, as a string raised wrong exception: %s" % str(x))
  1594. else:
  1595. self.fail("getaddrinfo for non-integer numeric port, as a string failed to raise exception")
  1596. # Check enforcement of AI_NUMERICSERV
  1597. try:
  1598. socket.getaddrinfo(hostname, "http", 0, 0, 0, socket.AI_NUMERICSERV)
  1599. except socket.gaierror, g:
  1600. self.failUnlessEqual(g[0], socket.EAI_NONAME)
  1601. except Exception, x:
  1602. self.fail("getaddrinfo for service name with AI_NUMERICSERV raised wrong exception: %s" % str(x))
  1603. else:
  1604. self.fail("getaddrinfo for service name with AI_NUMERICSERV failed to raise exception")
  1605. # Check treatment of non-existent service
  1606. try:
  1607. socket.getaddrinfo(hostname, "nosuchservice")
  1608. except socket.gaierror, g:
  1609. self.failUnlessEqual(g[0], socket.EAI_SERVICE)
  1610. except Exception, x:
  1611. self.fail("getaddrinfo for unknown service name raised wrong exception: %s" % str(x))
  1612. else:
  1613. self.fail("getaddrinfo for unknown service name failed to raise exception")
  1614. def testHostNames(self):
  1615. # None is only acceptable if AI_NUMERICHOST is not specified
  1616. for flags, expect_exception in [(0, False), (socket.AI_NUMERICHOST, True)]:
  1617. try:
  1618. socket.getaddrinfo(None, 80, 0, 0, 0, flags)
  1619. if expect_exception:
  1620. self.fail("Non-numeric hostname == None should have raised exception")
  1621. except Exception, x:
  1622. if not expect_exception:
  1623. self.fail("hostname == None should not have raised exception: %s" % str(x))
  1624. # Check enforcement of AI_NUMERICHOST
  1625. for host in ["", " ", "localhost"]:
  1626. try:
  1627. socket.getaddrinfo(host, 80, 0, 0, 0, socket.AI_NUMERICHOST)
  1628. except socket.gaierror, ge:
  1629. self.failUnlessEqual(ge[0], socket.EAI_NONAME)
  1630. except Exception, x:
  1631. self.fail("Non-numeric host with AI_NUMERICHOST raised wrong exception: %s" % str(x))
  1632. else:
  1633. self.fail("Non-numeric hostname '%s' with AI_NUMERICHOST should have raised exception" % host)
  1634. # Check enforcement of AI_NUMERICHOST with wrong address families
  1635. for host, family in [("127.0.0.1", socket.AF_INET6), ("::1", socket.AF_INET)]:
  1636. try:
  1637. socket.getaddrinfo(host, 80, family, 0, 0, socket.AI_NUMERICHOST)
  1638. except socket.gaierror, ge:
  1639. self.failUnlessEqual(ge[0], socket.EAI_ADDRFAMILY)
  1640. except Exception, x:
  1641. self.fail("Numeric host '%s' in wrong family '%s' with AI_NUMERICHOST raised wrong exception: %s" %
  1642. (host, family, str(x)) )
  1643. else:
  1644. self.fail("Numeric host '%s' in wrong family '%s' with AI_NUMERICHOST should have raised exception" %
  1645. (host, family) )
  1646. class TestGetNameInfo(unittest.TestCase):
  1647. def testBadParameters(self):
  1648. for address, flags in [
  1649. ( (0,0), 0),
  1650. ( (0,"http"), 0),
  1651. ( "localhost", 0),
  1652. ( 0, 0),
  1653. ( ("",), 0),
  1654. ]:
  1655. try:
  1656. socket.getnameinfo(address, flags)
  1657. except TypeError:
  1658. pass
  1659. except Exception, x:
  1660. self.fail("Bad getnameinfo parameters (%s, %s) raised wrong exception: %s" % (str(address), flags, str(x)))
  1661. else:
  1662. self.fail("Bad getnameinfo parameters (%s, %s) failed to raise exception" % (str(address), flags))
  1663. def testPort(self):
  1664. for address, flags, expected in [
  1665. ( ("127.0.0.1", 25), 0, "smtp" ),
  1666. ( ("127.0.0.1", 25), socket.NI_NUMERICSERV, 25 ),
  1667. ( ("127.0.0.1", 513), socket.NI_DGRAM, "who" ),
  1668. ( ("127.0.0.1", 513), 0, "login"),
  1669. ]:
  1670. result = socket.getnameinfo(address, flags)
  1671. self.failUnlessEqual(result[1], expected)
  1672. def testHost(self):
  1673. for address, flags, expected in [
  1674. ( ("www.python.org", 80), 0, "dinsdale.python.org"),
  1675. ( ("www.python.org", 80), socket.NI_NUMERICHOST, "82.94.164.162" ),
  1676. ( ("www.python.org", 80), socket.NI_NAMEREQD, "dinsdale.python.org"),
  1677. ( ("82.94.164.162", 80), socket.NI_NAMEREQD, "dinsdale.python.org"),
  1678. ]:
  1679. result = socket.getnameinfo(address, flags)
  1680. self.failUnlessEqual(result[0], expected)
  1681. def testNI_NAMEREQD(self):
  1682. # This test may delay for some seconds
  1683. unreversible_address = "198.51.100.1"
  1684. try:
  1685. socket.getnameinfo( (unreversible_address, 80), socket.NI_NAMEREQD)
  1686. except socket.gaierror, ge:
  1687. self.failUnlessEqual(ge[0], socket.EAI_NONAME)
  1688. except Exception, x:
  1689. self.fail("Unreversible address with NI_NAMEREQD (%s) raised wrong exception: %s" % (unreversible_address, str(x)))
  1690. else:
  1691. self.fail("Unreversible address with NI_NAMEREQD (%s) failed to raise exception" % unreversible_address)
  1692. def testHostIdna(self):
  1693. fqdn = u"\u043f\u0440\u0430\u0432\u0438\u0442\u0435\u043b\u044c\u0441\u0442\u0432\u043e.\u0440\u0444"
  1694. idn = "xn--80aealotwbjpid2k.xn--p1ai"
  1695. ip = "95.173.135.62"
  1696. try:
  1697. import java.net.IDN
  1698. except ImportError:
  1699. try:
  1700. socket.getnameinfo( (fqdn, 80), 0)
  1701. except UnicodeEncodeError:
  1702. pass
  1703. except Exception, x:
  1704. self.fail("International domain without java.net.IDN raised wrong exception: %s" % str(x))
  1705. else:
  1706. self.fail("International domain without java.net.IDN failed to raise exception")
  1707. else:
  1708. # have to disable this test until I find an IDN that reverses to the punycode name
  1709. return
  1710. for address, flags, expected in [
  1711. ( (fqdn, 80), 0, idn ),
  1712. ( (fqdn, 80), socket.NI_IDN, fqdn ),
  1713. ]:
  1714. result = socket.getnameinfo(address, flags)
  1715. self.failUnlessEqual(result[0], expected)
  1716. class TestJython_get_jsockaddr(unittest.TestCase):
  1717. "These tests are specific to jython: they test a key internal routine"
  1718. def testIPV4AddressesFromGetAddrInfo(self):
  1719. local_addr = socket.getaddrinfo("localhost", 80, socket.AF_INET, socket.SOCK_STREAM, 0, 0)[0][4]
  1720. sockaddr = socket._get_jsockaddr(local_addr, socket.AF_INET, None, 0, 0)
  1721. self.failUnless(isinstance(sockaddr, java.net.InetSocketAddress), "_get_jsockaddr returned wrong type: '%s'" % str(type(sockaddr)))
  1722. self.failUnlessEqual(sockaddr.address.hostAddress, "127.0.0.1")
  1723. self.failUnlessEqual(sockaddr.port, 80)
  1724. def testIPV6AddressesFromGetAddrInfo(self):
  1725. addrinfo = socket.getaddrinfo("localhost", 80, socket.AF_INET6, socket.SOCK_STREAM, 0, 0)
  1726. if not addrinfo and is_bsd:
  1727. # older FreeBSDs may have spotty IPV6 Java support
  1728. return
  1729. local_addr = addrinfo[0][4]
  1730. sockaddr = socket._get_jsockaddr(local_addr, socket.AF_INET6, None, 0, 0)
  1731. self.failUnless(isinstance(sockaddr, java.net.InetSocketAddress), "_get_jsockaddr returned wrong type: '%s'" % str(type(sockaddr)))
  1732. self.failUnless(sockaddr.address.hostAddress in ["::1", "0:0:0:0:0:0:0:1"])
  1733. self.failUnlessEqual(sockaddr.port, 80)
  1734. def testAddressesFrom2Tuple(self):
  1735. for family, addr_tuple, jaddress_type, expected in [
  1736. (socket.AF_INET, ("localhost", 80), java.net.Inet4Address, ["127.0.0.1"]),
  1737. (socket.AF_INET6, ("localhost", 80), java.net.Inet6Address, ["::1", "0:0:0:0:0:0:0:1"]),
  1738. ]:
  1739. sockaddr = socket._get_jsockaddr(addr_tuple, family, 0, 0, 0)
  1740. self.failUnless(isinstance(sockaddr, java.net.InetSocketAddress), "_get_jsockaddr returned wrong type: '%s'" % str(type(sockaddr)))
  1741. self.failUnless(isinstance(sockaddr.address, jaddress_type), "_get_jsockaddr returned wrong address type: '%s'(family=%d)" % (str(type(sockaddr.address)), family))
  1742. self.failUnless(sockaddr.address.hostAddress in expected)
  1743. self.failUnlessEqual(sockaddr.port, 80)
  1744. def testAddressesFrom4Tuple(self):
  1745. for addr_tuple in [
  1746. ("localhost", 80),
  1747. ("localhost", 80, 0, 0),
  1748. ]:
  1749. sockaddr = socket._get_jsockaddr(addr_tuple, socket.AF_INET6, 0, 0, 0)
  1750. self.failUnless(isinstance(sockaddr, java.net.InetSocketAddress), "_get_jsockaddr returned wrong type: '%s'" % str(type(sockaddr)))
  1751. self.failUnless(isinstance(sockaddr.address, java.net.Inet6Address), "_get_jsockaddr returned wrong address type: '%s'" % str(type(sockaddr.address)))
  1752. self.failUnless(sockaddr.address.hostAddress in ["::1", "0:0:0:0:0:0:0:1"])
  1753. self.failUnlessEqual(sockaddr.address.scopeId, 0)
  1754. self.failUnlessEqual(sockaddr.port, 80)
  1755. def testSpecialHostnames(self):
  1756. for family, sock_type, flags, addr_tuple, expected in [
  1757. ( socket.AF_INET, 0, 0, ("", 80), ["localhost"]),
  1758. ( socket.AF_INET, 0, socket.AI_PASSIVE, ("", 80), [socket.INADDR_ANY]),
  1759. ( socket.AF_INET6, 0, 0, ("", 80), ["localhost"]),
  1760. ( socket.AF_INET6, 0, socket.AI_PASSIVE, ("", 80), [socket.IN6ADDR_ANY_INIT, "0:0:0:0:0:0:0:0"]),
  1761. ( socket.AF_INET, socket.SOCK_DGRAM, 0, ("<broadcast>", 80), [socket.INADDR_BROADCAST]),
  1762. ]:
  1763. sockaddr = socket._get_jsockaddr(addr_tuple, family, sock_type, 0, flags)
  1764. self.failUnless(sockaddr.hostName in expected, "_get_jsockaddr returned wrong hostname '%s' for special hostname '%s'(family=%d)" % (sockaddr.hostName, addr_tuple[0], family))
  1765. def testNoneTo_get_jsockaddr(self):
  1766. for family, flags, expected in [
  1767. ( socket.AF_INET, 0, ["localhost"]),
  1768. ( socket.AF_INET, socket.AI_PASSIVE, [socket.INADDR_ANY]),
  1769. ( socket.AF_INET6, 0, ["localhost"]),
  1770. ( socket.AF_INET6, socket.AI_PASSIVE, [socket.IN6ADDR_ANY_INIT, "0:0:0:0:0:0:0:0"]),
  1771. ]:
  1772. sockaddr = socket._get_jsockaddr(None, family, 0, 0, flags)
  1773. self.failUnless(sockaddr.hostName in expected, "_get_jsockaddr returned wrong hostname '%s' for sock tuple == None (family=%d)" % (sockaddr.hostName, family))
  1774. def testBadAddressTuples(self):
  1775. for family, address_tuple in [
  1776. ( socket.AF_INET, () ),
  1777. ( socket.AF_INET, ("") ),
  1778. ( socket.AF_INET, (80) ),
  1779. ( socket.AF_INET, ("localhost", 80, 0) ),
  1780. ( socket.AF_INET, ("localhost", 80, 0, 0) ),
  1781. ( socket.AF_INET6, () ),
  1782. ( socket.AF_INET6, ("") ),
  1783. ( socket.AF_INET6, (80) ),
  1784. ( socket.AF_INET6, ("localhost", 80, 0) ),
  1785. ]:
  1786. try:
  1787. sockaddr = socket._get_jsockaddr(address_tuple, family, None, 0, 0)
  1788. except TypeError:
  1789. pass
  1790. else:
  1791. self.fail("Bad tuple %s (family=%d) should have raised TypeError" % (str(address_tuple), family))
  1792. class TestExceptions(unittest.TestCase):
  1793. def testExceptionTree(self):
  1794. self.assert_(issubclass(socket.error, IOError))
  1795. self.assert_(issubclass(socket.herror, socket.error))
  1796. self.assert_(issubclass(socket.gaierror, socket.error))
  1797. self.assert_(issubclass(socket.timeout, socket.error))
  1798. def testExceptionAtributes(self):
  1799. for exc_class_name in ['error', 'herror', 'gaierror', 'timeout']:
  1800. exc_class = getattr(socket, exc_class_name)
  1801. exc = exc_class(12345, "Expected message")
  1802. self.failUnlessEqual(getattr(exc, 'errno'), 12345, "Socket module exceptions must have an 'errno' attribute")
  1803. self.failUnlessEqual(getattr(exc, 'strerror'), "Expected message", "Socket module exceptions must have an 'strerror' attribute")
  1804. class TestJythonExceptionsShared:
  1805. def tearDown(self):
  1806. self.s.close()
  1807. self.s = None
  1808. def testHostNotFound(self):
  1809. try:
  1810. socket.gethostbyname("doesnotexist")
  1811. except socket.gaierror, gaix:
  1812. self.failUnlessEqual(gaix[0], errno.EGETADDRINFOFAILED)
  1813. except Exception, x:
  1814. self.fail("Get host name for non-existent host raised wrong exception: %s" % x)
  1815. def testUnresolvedAddress(self):
  1816. try:
  1817. self.s.connect( ('non.existent.server', PORT) )
  1818. except socket.gaierror, gaix:
  1819. self.failUnlessEqual(gaix[0], errno.EGETADDRINFOFAILED)
  1820. except Exception, x:
  1821. self.fail("Get host name for non-existent host raised wrong exception: %s" % x)
  1822. else:
  1823. self.fail("Get host name for non-existent host should have raised exception")
  1824. def testSocketNotConnected(self):
  1825. try:
  1826. self.s.send(MSG)
  1827. except socket.error, se:
  1828. self.failUnlessEqual(se[0], errno.ENOTCONN)
  1829. except Exception, x:
  1830. self.fail("Send on unconnected socket raised wrong exception: %s" % x)
  1831. else:
  1832. self.fail("Send on unconnected socket raised exception")
  1833. def testSocketNotBound(self):
  1834. try:
  1835. result = self.s.recv(1024)
  1836. except socket.error, se:
  1837. self.failUnlessEqual(se[0], errno.ENOTCONN)
  1838. except Exception, x:
  1839. self.fail("Receive on unbound socket raised wrong exception: %s" % x)
  1840. else:
  1841. self.fail("Receive on unbound socket raised exception")
  1842. def testClosedSocket(self):
  1843. self.s.close()
  1844. try:
  1845. self.s.send(MSG)
  1846. except socket.error, se:
  1847. self.failUnlessEqual(se[0], errno.EBADF)
  1848. dup = self.s.dup()
  1849. try:
  1850. dup.send(MSG)
  1851. except socket.error, se:
  1852. self.failUnlessEqual(se[0], errno.EBADF)
  1853. fp = self.s.makefile()
  1854. try:
  1855. fp.write(MSG)
  1856. fp.flush()
  1857. except socket.error, se:
  1858. self.failUnlessEqual(se[0], errno.EBADF)
  1859. class TestJythonTCPExceptions(TestJythonExceptionsShared, unittest.TestCase):
  1860. def setUp(self):
  1861. self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  1862. self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  1863. def testConnectionRefused(self):
  1864. try:
  1865. # This port should not be open at this time
  1866. self.s.connect( (HOST, PORT) )
  1867. except socket.error, se:
  1868. self.failUnlessEqual(se[0], errno.ECONNREFUSED)
  1869. except Exception, x:
  1870. self.fail("Connection to non-existent host/port raised wrong exception: %s" % x)
  1871. else:
  1872. self.fail("Socket (%s,%s) should not have been listening at this time" % (HOST, PORT))
  1873. def testBindException(self):
  1874. # First bind to the target port
  1875. self.s.bind( (HOST, PORT) )
  1876. self.s.listen(50)
  1877. try:
  1878. # And then try to bind again
  1879. t = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  1880. t.bind( (HOST, PORT) )
  1881. t.listen(50)
  1882. except socket.error, se:
  1883. self.failUnlessEqual(se[0], errno.EADDRINUSE)
  1884. except Exception, x:
  1885. self.fail("Binding to already bound host/port raised wrong exception: %s" % x)
  1886. else:
  1887. self.fail("Binding to already bound host/port should have raised exception")
  1888. class TestJythonUDPExceptions(TestJythonExceptionsShared, unittest.TestCase):
  1889. def setUp(self):
  1890. self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  1891. self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  1892. def testBindException(self):
  1893. # First bind to the target port
  1894. self.s.bind( (HOST, PORT) )
  1895. try:
  1896. # And then try to bind again
  1897. t = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  1898. t.bind( (HOST, PORT) )
  1899. except socket.error, se:
  1900. self.failUnlessEqual(se[0], errno.EADDRINUSE)
  1901. except Exception, x:
  1902. self.fail("Binding to already bound host/port raised wrong exception: %s" % x)
  1903. else:
  1904. self.fail("Binding to already bound host/port should have raised exception")
  1905. class TestAddressParameters:
  1906. def testBindNonTupleEndpointRaisesTypeError(self):
  1907. try:
  1908. self.socket.bind(HOST, PORT)
  1909. except TypeError:
  1910. pass
  1911. else:
  1912. self.fail("Illegal non-tuple bind address did not raise TypeError")
  1913. def testConnectNonTupleEndpointRaisesTypeError(self):
  1914. try:
  1915. self.socket.connect(HOST, PORT)
  1916. except TypeError:
  1917. pass
  1918. else:
  1919. self.fail("Illegal non-tuple connect address did not raise TypeError")
  1920. def testConnectExNonTupleEndpointRaisesTypeError(self):
  1921. try:
  1922. self.socket.connect_ex(HOST, PORT)
  1923. except TypeError:
  1924. pass
  1925. else:
  1926. self.fail("Illegal non-tuple connect address did not raise TypeError")
  1927. class TestTCPAddressParameters(unittest.TestCase, TestAddressParameters):
  1928. def setUp(self):
  1929. self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  1930. class TestUDPAddressParameters(unittest.TestCase, TestAddressParameters):
  1931. def setUp(self):
  1932. self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  1933. class UnicodeTest(ThreadedTCPSocketTest):
  1934. def testUnicodeHostname(self):
  1935. pass
  1936. def _testUnicodeHostname(self):
  1937. self.cli.connect((unicode(self.HOST), self.PORT))
  1938. class IDNATest(unittest.TestCase):
  1939. def testGetAddrInfoIDNAHostname(self):
  1940. idna_domain = u"al\u00e1n.com"
  1941. if socket.supports('idna'):
  1942. try:
  1943. addresses = socket.getaddrinfo(idna_domain, 80)
  1944. self.failUnless(len(addresses) > 0, "No addresses returned for test IDNA domain '%s'" % repr(idna_domain))
  1945. except Exception, x:
  1946. self.fail("Unexpected exception raised for socket.getaddrinfo(%s)" % repr(idna_domain))
  1947. else:
  1948. try:
  1949. socket.getaddrinfo(idna_domain, 80)
  1950. except UnicodeEncodeError:
  1951. pass
  1952. except Exception, x:
  1953. self.fail("Non ascii domain '%s' should have raised UnicodeEncodeError, not %s" % (repr(idna_domain), str(x)))
  1954. else:
  1955. self.fail("Non ascii domain '%s' should have raised UnicodeEncodeError: no exception raised" % repr(idna_domain))
  1956. def testAddrTupleIDNAHostname(self):
  1957. idna_domain = u"al\u00e1n.com"
  1958. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  1959. if socket.supports('idna'):
  1960. try:
  1961. s.bind( (idna_domain, 80) )
  1962. except socket.error:
  1963. # We're not worried about socket errors, i.e. bind problems, etc.
  1964. pass
  1965. except Exception, x:
  1966. self.fail("Unexpected exception raised for socket.bind(%s)" % repr(idna_domain))
  1967. else:
  1968. try:
  1969. s.bind( (idna_domain, 80) )
  1970. except UnicodeEncodeError:
  1971. pass
  1972. except Exception, x:
  1973. self.fail("Non ascii domain '%s' should have raised UnicodeEncodeError, not %s" % (repr(idna_domain), str(x)))
  1974. else:
  1975. self.fail("Non ascii domain '%s' should have raised UnicodeEncodeError: no exception raised" % repr(idna_domain))
  1976. class TestInvalidUsage(unittest.TestCase):
  1977. def setUp(self):
  1978. self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  1979. def testShutdownIOOnListener(self):
  1980. self.socket.listen(50) # socket is now a server socket
  1981. try:
  1982. self.socket.shutdown(socket.SHUT_RDWR)
  1983. except Exception, x:
  1984. self.fail("Shutdown on listening socket should not have raised socket exception, not %s" % str(x))
  1985. else:
  1986. pass
  1987. def testShutdownOnUnconnectedSocket(self):
  1988. try:
  1989. self.socket.shutdown(socket.SHUT_RDWR)
  1990. except socket.error, se:
  1991. self.failUnlessEqual(se[0], errno.ENOTCONN, "Shutdown on unconnected socket should have raised errno.ENOTCONN, not %s" % str(se[0]))
  1992. except Exception, x:
  1993. self.fail("Shutdown on unconnected socket should have raised socket exception, not %s" % str(x))
  1994. else:
  1995. self.fail("Shutdown on unconnected socket should have raised socket exception")
  1996. class TestGetSockAndPeerName:
  1997. def testGetpeernameNoImpl(self):
  1998. try:
  1999. self.s.getpeername()
  2000. except socket.error, se:
  2001. if se[0] == errno.ENOTCONN:
  2002. return
  2003. self.fail("getpeername() on unconnected socket should have raised socket.error")
  2004. def testGetsocknameUnboundNoImpl(self):
  2005. try:
  2006. self.s.getsockname()
  2007. except socket.error, se:
  2008. if se[0] == errno.EINVAL:
  2009. return
  2010. self.fail("getsockname() on unconnected socket should have raised socket.error")
  2011. def testGetsocknameBoundNoImpl(self):
  2012. self.s.bind( ("localhost", 0) )
  2013. try:
  2014. self.s.getsockname()
  2015. except socket.error, se:
  2016. self.fail("getsockname() on bound socket should have not raised socket.error")
  2017. def testGetsocknameImplCreated(self):
  2018. self._create_impl_socket()
  2019. try:
  2020. self.s.getsockname()
  2021. except socket.error, se:
  2022. self.fail("getsockname() on active socket should not have raised socket.error")
  2023. def tearDown(self):
  2024. self.s.close()
  2025. class TestGetSockAndPeerNameTCPClient(unittest.TestCase, TestGetSockAndPeerName):
  2026. def setUp(self):
  2027. self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  2028. # This server is not needed for all tests, but create it anyway
  2029. # It uses an ephemeral port, so there should be no port clashes or
  2030. # problems with reuse.
  2031. self.server_peer = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  2032. self.server_peer.bind( ("localhost", 0) )
  2033. self.server_peer.listen(5)
  2034. def _create_impl_socket(self):
  2035. self.s.connect(self.server_peer.getsockname())
  2036. def testGetpeernameImplCreated(self):
  2037. self._create_impl_socket()
  2038. try:
  2039. self.s.getpeername()
  2040. except socket.error, se:
  2041. self.fail("getpeername() on active socket should not have raised socket.error")
  2042. self.failUnlessEqual(self.s.getpeername(), self.server_peer.getsockname())
  2043. def tearDown(self):
  2044. self.server_peer.close()
  2045. class TestGetSockAndPeerNameTCPServer(unittest.TestCase, TestGetSockAndPeerName):
  2046. def setUp(self):
  2047. self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  2048. def _create_impl_socket(self):
  2049. self.s.bind(("localhost", 0))
  2050. self.s.listen(5)
  2051. def testGetpeernameImplCreated(self):
  2052. self._create_impl_socket()
  2053. try:
  2054. self.s.getpeername()
  2055. except socket.error, se:
  2056. if se[0] == errno.ENOTCONN:
  2057. return
  2058. self.fail("getpeername() on listening socket should have raised socket.error")
  2059. class TestGetSockAndPeerNameUDP(unittest.TestCase, TestGetSockAndPeerName):
  2060. def setUp(self):
  2061. self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  2062. def _create_impl_socket(self):
  2063. # Binding is enough to cause socket impl creation
  2064. self.s.bind(("localhost", 0))
  2065. def testGetpeernameImplCreatedNotConnected(self):
  2066. self._create_impl_socket()
  2067. try:
  2068. self.s.getpeername()
  2069. except socket.error, se:
  2070. if se[0] == errno.ENOTCONN:
  2071. return
  2072. self.fail("getpeername() on unconnected UDP socket should have raised socket.error")
  2073. def testGetpeernameImplCreatedAndConnected(self):
  2074. # This test also tests that an UDP socket can be bound and connected at the same time
  2075. self._create_impl_socket()
  2076. # Need to connect to an UDP port
  2077. self._udp_peer = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  2078. self._udp_peer.bind( ("localhost", 0) )
  2079. self.s.connect(self._udp_peer.getsockname())
  2080. try:
  2081. try:
  2082. self.s.getpeername()
  2083. except socket.error, se:
  2084. self.fail("getpeername() on connected UDP socket should not have raised socket.error")
  2085. self.failUnlessEqual(self.s.getpeername(), self._udp_peer.getsockname())
  2086. finally:
  2087. self._udp_peer.close()
  2088. def test_main():
  2089. tests = [
  2090. GeneralModuleTests,
  2091. IPAddressTests,
  2092. TestSupportedOptions,
  2093. TestPseudoOptions,
  2094. TestUnsupportedOptions,
  2095. BasicTCPTest,
  2096. TCPServerTimeoutTest,
  2097. TCPClientTimeoutTest,
  2098. TestExceptions,
  2099. TestInvalidUsage,
  2100. TestGetAddrInfo,
  2101. TestGetNameInfo,
  2102. TestTCPAddressParameters,
  2103. TestUDPAddressParameters,
  2104. UDPBindTest,
  2105. BasicUDPTest,
  2106. UDPTimeoutTest,
  2107. NonBlockingTCPTests,
  2108. NonBlockingUDPTests,
  2109. TCPFileObjectClassOpenCloseTests,
  2110. UDPFileObjectClassOpenCloseTests,
  2111. FileAndDupOpenCloseTests,
  2112. FileObjectClassTestCase,
  2113. PrivateFileObjectTestCase,
  2114. UnbufferedFileObjectClassTestCase,
  2115. LineBufferedFileObjectClassTestCase,
  2116. SmallBufferedFileObjectClassTestCase,
  2117. UnicodeTest,
  2118. IDNATest,
  2119. TestGetSockAndPeerNameTCPClient,
  2120. TestGetSockAndPeerNameTCPServer,
  2121. TestGetSockAndPeerNameUDP,
  2122. ]
  2123. if hasattr(socket, "socketpair"):
  2124. tests.append(BasicSocketPairTest)
  2125. if sys.platform[:4] == 'java':
  2126. tests.append(TestJythonTCPExceptions)
  2127. tests.append(TestJythonUDPExceptions)
  2128. tests.append(TestJython_get_jsockaddr)
  2129. # TODO: Broadcast requires permission, and is blocked by some firewalls
  2130. # Need some way to discover the network setup on the test machine
  2131. if False:
  2132. tests.append(UDPBroadcastTest)
  2133. suites = [unittest.makeSuite(klass, 'test') for klass in tests]
  2134. test_support._run_suite(unittest.TestSuite(suites))
  2135. if __name__ == "__main__":
  2136. test_main()