PageRenderTime 64ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/Lib/test/test_socket.py

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