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

/Lib/test/test_socket.py

https://bitbucket.org/python_mirrors/releasing-2.7.3
Python | 4708 lines | 4415 code | 149 blank | 144 comment | 40 complexity | a0c969ec54619ce8aed5ee5c696d944c MD5 | raw file
Possible License(s): BSD-3-Clause, 0BSD

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

  1. #!/usr/bin/env python3
  2. import unittest
  3. from test import support
  4. import errno
  5. import io
  6. import socket
  7. import select
  8. import tempfile
  9. import _testcapi
  10. import time
  11. import traceback
  12. import queue
  13. import sys
  14. import os
  15. import array
  16. import platform
  17. import contextlib
  18. from weakref import proxy
  19. import signal
  20. import math
  21. import pickle
  22. import struct
  23. try:
  24. import fcntl
  25. except ImportError:
  26. fcntl = False
  27. HOST = support.HOST
  28. MSG = 'Michael Gilfix was here\u1234\r\n'.encode('utf-8') ## test unicode string and carriage return
  29. try:
  30. import _thread as thread
  31. import threading
  32. except ImportError:
  33. thread = None
  34. threading = None
  35. def _have_socket_can():
  36. """Check whether CAN sockets are supported on this host."""
  37. try:
  38. s = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
  39. except (AttributeError, socket.error, OSError):
  40. return False
  41. else:
  42. s.close()
  43. return True
  44. def _have_socket_rds():
  45. """Check whether RDS sockets are supported on this host."""
  46. try:
  47. s = socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0)
  48. except (AttributeError, OSError):
  49. return False
  50. else:
  51. s.close()
  52. return True
  53. HAVE_SOCKET_CAN = _have_socket_can()
  54. HAVE_SOCKET_RDS = _have_socket_rds()
  55. # Size in bytes of the int type
  56. SIZEOF_INT = array.array("i").itemsize
  57. class SocketTCPTest(unittest.TestCase):
  58. def setUp(self):
  59. self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  60. self.port = support.bind_port(self.serv)
  61. self.serv.listen(1)
  62. def tearDown(self):
  63. self.serv.close()
  64. self.serv = None
  65. class SocketUDPTest(unittest.TestCase):
  66. def setUp(self):
  67. self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  68. self.port = support.bind_port(self.serv)
  69. def tearDown(self):
  70. self.serv.close()
  71. self.serv = None
  72. class ThreadSafeCleanupTestCase(unittest.TestCase):
  73. """Subclass of unittest.TestCase with thread-safe cleanup methods.
  74. This subclass protects the addCleanup() and doCleanups() methods
  75. with a recursive lock.
  76. """
  77. if threading:
  78. def __init__(self, *args, **kwargs):
  79. super().__init__(*args, **kwargs)
  80. self._cleanup_lock = threading.RLock()
  81. def addCleanup(self, *args, **kwargs):
  82. with self._cleanup_lock:
  83. return super().addCleanup(*args, **kwargs)
  84. def doCleanups(self, *args, **kwargs):
  85. with self._cleanup_lock:
  86. return super().doCleanups(*args, **kwargs)
  87. class SocketCANTest(unittest.TestCase):
  88. """To be able to run this test, a `vcan0` CAN interface can be created with
  89. the following commands:
  90. # modprobe vcan
  91. # ip link add dev vcan0 type vcan
  92. # ifconfig vcan0 up
  93. """
  94. interface = 'vcan0'
  95. bufsize = 128
  96. def setUp(self):
  97. self.s = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
  98. self.addCleanup(self.s.close)
  99. try:
  100. self.s.bind((self.interface,))
  101. except socket.error:
  102. self.skipTest('network interface `%s` does not exist' %
  103. self.interface)
  104. class SocketRDSTest(unittest.TestCase):
  105. """To be able to run this test, the `rds` kernel module must be loaded:
  106. # modprobe rds
  107. """
  108. bufsize = 8192
  109. def setUp(self):
  110. self.serv = socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0)
  111. self.addCleanup(self.serv.close)
  112. try:
  113. self.port = support.bind_port(self.serv)
  114. except OSError:
  115. self.skipTest('unable to bind RDS socket')
  116. class ThreadableTest:
  117. """Threadable Test class
  118. The ThreadableTest class makes it easy to create a threaded
  119. client/server pair from an existing unit test. To create a
  120. new threaded class from an existing unit test, use multiple
  121. inheritance:
  122. class NewClass (OldClass, ThreadableTest):
  123. pass
  124. This class defines two new fixture functions with obvious
  125. purposes for overriding:
  126. clientSetUp ()
  127. clientTearDown ()
  128. Any new test functions within the class must then define
  129. tests in pairs, where the test name is preceeded with a
  130. '_' to indicate the client portion of the test. Ex:
  131. def testFoo(self):
  132. # Server portion
  133. def _testFoo(self):
  134. # Client portion
  135. Any exceptions raised by the clients during their tests
  136. are caught and transferred to the main thread to alert
  137. the testing framework.
  138. Note, the server setup function cannot call any blocking
  139. functions that rely on the client thread during setup,
  140. unless serverExplicitReady() is called just before
  141. the blocking call (such as in setting up a client/server
  142. connection and performing the accept() in setUp().
  143. """
  144. def __init__(self):
  145. # Swap the true setup function
  146. self.__setUp = self.setUp
  147. self.__tearDown = self.tearDown
  148. self.setUp = self._setUp
  149. self.tearDown = self._tearDown
  150. def serverExplicitReady(self):
  151. """This method allows the server to explicitly indicate that
  152. it wants the client thread to proceed. This is useful if the
  153. server is about to execute a blocking routine that is
  154. dependent upon the client thread during its setup routine."""
  155. self.server_ready.set()
  156. def _setUp(self):
  157. self.server_ready = threading.Event()
  158. self.client_ready = threading.Event()
  159. self.done = threading.Event()
  160. self.queue = queue.Queue(1)
  161. self.server_crashed = False
  162. # Do some munging to start the client test.
  163. methodname = self.id()
  164. i = methodname.rfind('.')
  165. methodname = methodname[i+1:]
  166. test_method = getattr(self, '_' + methodname)
  167. self.client_thread = thread.start_new_thread(
  168. self.clientRun, (test_method,))
  169. try:
  170. self.__setUp()
  171. except:
  172. self.server_crashed = True
  173. raise
  174. finally:
  175. self.server_ready.set()
  176. self.client_ready.wait()
  177. def _tearDown(self):
  178. self.__tearDown()
  179. self.done.wait()
  180. if self.queue.qsize():
  181. exc = self.queue.get()
  182. raise exc
  183. def clientRun(self, test_func):
  184. self.server_ready.wait()
  185. self.clientSetUp()
  186. self.client_ready.set()
  187. if self.server_crashed:
  188. self.clientTearDown()
  189. return
  190. if not hasattr(test_func, '__call__'):
  191. raise TypeError("test_func must be a callable function")
  192. try:
  193. test_func()
  194. except unittest._ExpectedFailure:
  195. # We deliberately ignore expected failures
  196. pass
  197. except BaseException as e:
  198. self.queue.put(e)
  199. finally:
  200. self.clientTearDown()
  201. def clientSetUp(self):
  202. raise NotImplementedError("clientSetUp must be implemented.")
  203. def clientTearDown(self):
  204. self.done.set()
  205. thread.exit()
  206. class ThreadedTCPSocketTest(SocketTCPTest, ThreadableTest):
  207. def __init__(self, methodName='runTest'):
  208. SocketTCPTest.__init__(self, methodName=methodName)
  209. ThreadableTest.__init__(self)
  210. def clientSetUp(self):
  211. self.cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  212. def clientTearDown(self):
  213. self.cli.close()
  214. self.cli = None
  215. ThreadableTest.clientTearDown(self)
  216. class ThreadedUDPSocketTest(SocketUDPTest, ThreadableTest):
  217. def __init__(self, methodName='runTest'):
  218. SocketUDPTest.__init__(self, methodName=methodName)
  219. ThreadableTest.__init__(self)
  220. def clientSetUp(self):
  221. self.cli = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  222. def clientTearDown(self):
  223. self.cli.close()
  224. self.cli = None
  225. ThreadableTest.clientTearDown(self)
  226. class ThreadedCANSocketTest(SocketCANTest, ThreadableTest):
  227. def __init__(self, methodName='runTest'):
  228. SocketCANTest.__init__(self, methodName=methodName)
  229. ThreadableTest.__init__(self)
  230. def clientSetUp(self):
  231. self.cli = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
  232. try:
  233. self.cli.bind((self.interface,))
  234. except socket.error:
  235. # skipTest should not be called here, and will be called in the
  236. # server instead
  237. pass
  238. def clientTearDown(self):
  239. self.cli.close()
  240. self.cli = None
  241. ThreadableTest.clientTearDown(self)
  242. class ThreadedRDSSocketTest(SocketRDSTest, ThreadableTest):
  243. def __init__(self, methodName='runTest'):
  244. SocketRDSTest.__init__(self, methodName=methodName)
  245. ThreadableTest.__init__(self)
  246. def clientSetUp(self):
  247. self.cli = socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0)
  248. try:
  249. # RDS sockets must be bound explicitly to send or receive data
  250. self.cli.bind((HOST, 0))
  251. self.cli_addr = self.cli.getsockname()
  252. except OSError:
  253. # skipTest should not be called here, and will be called in the
  254. # server instead
  255. pass
  256. def clientTearDown(self):
  257. self.cli.close()
  258. self.cli = None
  259. ThreadableTest.clientTearDown(self)
  260. class SocketConnectedTest(ThreadedTCPSocketTest):
  261. """Socket tests for client-server connection.
  262. self.cli_conn is a client socket connected to the server. The
  263. setUp() method guarantees that it is connected to the server.
  264. """
  265. def __init__(self, methodName='runTest'):
  266. ThreadedTCPSocketTest.__init__(self, methodName=methodName)
  267. def setUp(self):
  268. ThreadedTCPSocketTest.setUp(self)
  269. # Indicate explicitly we're ready for the client thread to
  270. # proceed and then perform the blocking call to accept
  271. self.serverExplicitReady()
  272. conn, addr = self.serv.accept()
  273. self.cli_conn = conn
  274. def tearDown(self):
  275. self.cli_conn.close()
  276. self.cli_conn = None
  277. ThreadedTCPSocketTest.tearDown(self)
  278. def clientSetUp(self):
  279. ThreadedTCPSocketTest.clientSetUp(self)
  280. self.cli.connect((HOST, self.port))
  281. self.serv_conn = self.cli
  282. def clientTearDown(self):
  283. self.serv_conn.close()
  284. self.serv_conn = None
  285. ThreadedTCPSocketTest.clientTearDown(self)
  286. class SocketPairTest(unittest.TestCase, ThreadableTest):
  287. def __init__(self, methodName='runTest'):
  288. unittest.TestCase.__init__(self, methodName=methodName)
  289. ThreadableTest.__init__(self)
  290. def setUp(self):
  291. self.serv, self.cli = socket.socketpair()
  292. def tearDown(self):
  293. self.serv.close()
  294. self.serv = None
  295. def clientSetUp(self):
  296. pass
  297. def clientTearDown(self):
  298. self.cli.close()
  299. self.cli = None
  300. ThreadableTest.clientTearDown(self)
  301. # The following classes are used by the sendmsg()/recvmsg() tests.
  302. # Combining, for instance, ConnectedStreamTestMixin and TCPTestBase
  303. # gives a drop-in replacement for SocketConnectedTest, but different
  304. # address families can be used, and the attributes serv_addr and
  305. # cli_addr will be set to the addresses of the endpoints.
  306. class SocketTestBase(unittest.TestCase):
  307. """A base class for socket tests.
  308. Subclasses must provide methods newSocket() to return a new socket
  309. and bindSock(sock) to bind it to an unused address.
  310. Creates a socket self.serv and sets self.serv_addr to its address.
  311. """
  312. def setUp(self):
  313. self.serv = self.newSocket()
  314. self.bindServer()
  315. def bindServer(self):
  316. """Bind server socket and set self.serv_addr to its address."""
  317. self.bindSock(self.serv)
  318. self.serv_addr = self.serv.getsockname()
  319. def tearDown(self):
  320. self.serv.close()
  321. self.serv = None
  322. class SocketListeningTestMixin(SocketTestBase):
  323. """Mixin to listen on the server socket."""
  324. def setUp(self):
  325. super().setUp()
  326. self.serv.listen(1)
  327. class ThreadedSocketTestMixin(ThreadSafeCleanupTestCase, SocketTestBase,
  328. ThreadableTest):
  329. """Mixin to add client socket and allow client/server tests.
  330. Client socket is self.cli and its address is self.cli_addr. See
  331. ThreadableTest for usage information.
  332. """
  333. def __init__(self, *args, **kwargs):
  334. super().__init__(*args, **kwargs)
  335. ThreadableTest.__init__(self)
  336. def clientSetUp(self):
  337. self.cli = self.newClientSocket()
  338. self.bindClient()
  339. def newClientSocket(self):
  340. """Return a new socket for use as client."""
  341. return self.newSocket()
  342. def bindClient(self):
  343. """Bind client socket and set self.cli_addr to its address."""
  344. self.bindSock(self.cli)
  345. self.cli_addr = self.cli.getsockname()
  346. def clientTearDown(self):
  347. self.cli.close()
  348. self.cli = None
  349. ThreadableTest.clientTearDown(self)
  350. class ConnectedStreamTestMixin(SocketListeningTestMixin,
  351. ThreadedSocketTestMixin):
  352. """Mixin to allow client/server stream tests with connected client.
  353. Server's socket representing connection to client is self.cli_conn
  354. and client's connection to server is self.serv_conn. (Based on
  355. SocketConnectedTest.)
  356. """
  357. def setUp(self):
  358. super().setUp()
  359. # Indicate explicitly we're ready for the client thread to
  360. # proceed and then perform the blocking call to accept
  361. self.serverExplicitReady()
  362. conn, addr = self.serv.accept()
  363. self.cli_conn = conn
  364. def tearDown(self):
  365. self.cli_conn.close()
  366. self.cli_conn = None
  367. super().tearDown()
  368. def clientSetUp(self):
  369. super().clientSetUp()
  370. self.cli.connect(self.serv_addr)
  371. self.serv_conn = self.cli
  372. def clientTearDown(self):
  373. self.serv_conn.close()
  374. self.serv_conn = None
  375. super().clientTearDown()
  376. class UnixSocketTestBase(SocketTestBase):
  377. """Base class for Unix-domain socket tests."""
  378. # This class is used for file descriptor passing tests, so we
  379. # create the sockets in a private directory so that other users
  380. # can't send anything that might be problematic for a privileged
  381. # user running the tests.
  382. def setUp(self):
  383. self.dir_path = tempfile.mkdtemp()
  384. self.addCleanup(os.rmdir, self.dir_path)
  385. super().setUp()
  386. def bindSock(self, sock):
  387. path = tempfile.mktemp(dir=self.dir_path)
  388. sock.bind(path)
  389. self.addCleanup(support.unlink, path)
  390. class UnixStreamBase(UnixSocketTestBase):
  391. """Base class for Unix-domain SOCK_STREAM tests."""
  392. def newSocket(self):
  393. return socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  394. class InetTestBase(SocketTestBase):
  395. """Base class for IPv4 socket tests."""
  396. host = HOST
  397. def setUp(self):
  398. super().setUp()
  399. self.port = self.serv_addr[1]
  400. def bindSock(self, sock):
  401. support.bind_port(sock, host=self.host)
  402. class TCPTestBase(InetTestBase):
  403. """Base class for TCP-over-IPv4 tests."""
  404. def newSocket(self):
  405. return socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  406. class UDPTestBase(InetTestBase):
  407. """Base class for UDP-over-IPv4 tests."""
  408. def newSocket(self):
  409. return socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  410. class SCTPStreamBase(InetTestBase):
  411. """Base class for SCTP tests in one-to-one (SOCK_STREAM) mode."""
  412. def newSocket(self):
  413. return socket.socket(socket.AF_INET, socket.SOCK_STREAM,
  414. socket.IPPROTO_SCTP)
  415. class Inet6TestBase(InetTestBase):
  416. """Base class for IPv6 socket tests."""
  417. # Don't use "localhost" here - it may not have an IPv6 address
  418. # assigned to it by default (e.g. in /etc/hosts), and if someone
  419. # has assigned it an IPv4-mapped address, then it's unlikely to
  420. # work with the full IPv6 API.
  421. host = "::1"
  422. class UDP6TestBase(Inet6TestBase):
  423. """Base class for UDP-over-IPv6 tests."""
  424. def newSocket(self):
  425. return socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
  426. # Test-skipping decorators for use with ThreadableTest.
  427. def skipWithClientIf(condition, reason):
  428. """Skip decorated test if condition is true, add client_skip decorator.
  429. If the decorated object is not a class, sets its attribute
  430. "client_skip" to a decorator which will return an empty function
  431. if the test is to be skipped, or the original function if it is
  432. not. This can be used to avoid running the client part of a
  433. skipped test when using ThreadableTest.
  434. """
  435. def client_pass(*args, **kwargs):
  436. pass
  437. def skipdec(obj):
  438. retval = unittest.skip(reason)(obj)
  439. if not isinstance(obj, type):
  440. retval.client_skip = lambda f: client_pass
  441. return retval
  442. def noskipdec(obj):
  443. if not (isinstance(obj, type) or hasattr(obj, "client_skip")):
  444. obj.client_skip = lambda f: f
  445. return obj
  446. return skipdec if condition else noskipdec
  447. def requireAttrs(obj, *attributes):
  448. """Skip decorated test if obj is missing any of the given attributes.
  449. Sets client_skip attribute as skipWithClientIf() does.
  450. """
  451. missing = [name for name in attributes if not hasattr(obj, name)]
  452. return skipWithClientIf(
  453. missing, "don't have " + ", ".join(name for name in missing))
  454. def requireSocket(*args):
  455. """Skip decorated test if a socket cannot be created with given arguments.
  456. When an argument is given as a string, will use the value of that
  457. attribute of the socket module, or skip the test if it doesn't
  458. exist. Sets client_skip attribute as skipWithClientIf() does.
  459. """
  460. err = None
  461. missing = [obj for obj in args if
  462. isinstance(obj, str) and not hasattr(socket, obj)]
  463. if missing:
  464. err = "don't have " + ", ".join(name for name in missing)
  465. else:
  466. callargs = [getattr(socket, obj) if isinstance(obj, str) else obj
  467. for obj in args]
  468. try:
  469. s = socket.socket(*callargs)
  470. except socket.error as e:
  471. # XXX: check errno?
  472. err = str(e)
  473. else:
  474. s.close()
  475. return skipWithClientIf(
  476. err is not None,
  477. "can't create socket({0}): {1}".format(
  478. ", ".join(str(o) for o in args), err))
  479. #######################################################################
  480. ## Begin Tests
  481. class GeneralModuleTests(unittest.TestCase):
  482. def test_repr(self):
  483. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  484. self.addCleanup(s.close)
  485. self.assertTrue(repr(s).startswith("<socket.socket object"))
  486. def test_weakref(self):
  487. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  488. p = proxy(s)
  489. self.assertEqual(p.fileno(), s.fileno())
  490. s.close()
  491. s = None
  492. try:
  493. p.fileno()
  494. except ReferenceError:
  495. pass
  496. else:
  497. self.fail('Socket proxy still exists')
  498. def testSocketError(self):
  499. # Testing socket module exceptions
  500. msg = "Error raising socket exception (%s)."
  501. with self.assertRaises(socket.error, msg=msg % 'socket.error'):
  502. raise socket.error
  503. with self.assertRaises(socket.error, msg=msg % 'socket.herror'):
  504. raise socket.herror
  505. with self.assertRaises(socket.error, msg=msg % 'socket.gaierror'):
  506. raise socket.gaierror
  507. def testSendtoErrors(self):
  508. # Testing that sendto doens't masks failures. See #10169.
  509. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  510. self.addCleanup(s.close)
  511. s.bind(('', 0))
  512. sockname = s.getsockname()
  513. # 2 args
  514. with self.assertRaises(TypeError) as cm:
  515. s.sendto('\u2620', sockname)
  516. self.assertEqual(str(cm.exception),
  517. "'str' does not support the buffer interface")
  518. with self.assertRaises(TypeError) as cm:
  519. s.sendto(5j, sockname)
  520. self.assertEqual(str(cm.exception),
  521. "'complex' does not support the buffer interface")
  522. with self.assertRaises(TypeError) as cm:
  523. s.sendto(b'foo', None)
  524. self.assertIn('not NoneType',str(cm.exception))
  525. # 3 args
  526. with self.assertRaises(TypeError) as cm:
  527. s.sendto('\u2620', 0, sockname)
  528. self.assertEqual(str(cm.exception),
  529. "'str' does not support the buffer interface")
  530. with self.assertRaises(TypeError) as cm:
  531. s.sendto(5j, 0, sockname)
  532. self.assertEqual(str(cm.exception),
  533. "'complex' does not support the buffer interface")
  534. with self.assertRaises(TypeError) as cm:
  535. s.sendto(b'foo', 0, None)
  536. self.assertIn('not NoneType', str(cm.exception))
  537. with self.assertRaises(TypeError) as cm:
  538. s.sendto(b'foo', 'bar', sockname)
  539. self.assertIn('an integer is required', str(cm.exception))
  540. with self.assertRaises(TypeError) as cm:
  541. s.sendto(b'foo', None, None)
  542. self.assertIn('an integer is required', str(cm.exception))
  543. # wrong number of args
  544. with self.assertRaises(TypeError) as cm:
  545. s.sendto(b'foo')
  546. self.assertIn('(1 given)', str(cm.exception))
  547. with self.assertRaises(TypeError) as cm:
  548. s.sendto(b'foo', 0, sockname, 4)
  549. self.assertIn('(4 given)', str(cm.exception))
  550. def testCrucialConstants(self):
  551. # Testing for mission critical constants
  552. socket.AF_INET
  553. socket.SOCK_STREAM
  554. socket.SOCK_DGRAM
  555. socket.SOCK_RAW
  556. socket.SOCK_RDM
  557. socket.SOCK_SEQPACKET
  558. socket.SOL_SOCKET
  559. socket.SO_REUSEADDR
  560. def testHostnameRes(self):
  561. # Testing hostname resolution mechanisms
  562. hostname = socket.gethostname()
  563. try:
  564. ip = socket.gethostbyname(hostname)
  565. except socket.error:
  566. # Probably name lookup wasn't set up right; skip this test
  567. return
  568. self.assertTrue(ip.find('.') >= 0, "Error resolving host to ip.")
  569. try:
  570. hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
  571. except socket.error:
  572. # Probably a similar problem as above; skip this test
  573. return
  574. all_host_names = [hostname, hname] + aliases
  575. fqhn = socket.getfqdn(ip)
  576. if not fqhn in all_host_names:
  577. self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names)))
  578. @unittest.skipUnless(hasattr(socket, 'sethostname'), "test needs socket.sethostname()")
  579. @unittest.skipUnless(hasattr(socket, 'gethostname'), "test needs socket.gethostname()")
  580. def test_sethostname(self):
  581. oldhn = socket.gethostname()
  582. try:
  583. socket.sethostname('new')
  584. except socket.error as e:
  585. if e.errno == errno.EPERM:
  586. self.skipTest("test should be run as root")
  587. else:
  588. raise
  589. try:
  590. # running test as root!
  591. self.assertEqual(socket.gethostname(), 'new')
  592. # Should work with bytes objects too
  593. socket.sethostname(b'bar')
  594. self.assertEqual(socket.gethostname(), 'bar')
  595. finally:
  596. socket.sethostname(oldhn)
  597. @unittest.skipUnless(hasattr(socket, 'if_nameindex'),
  598. 'socket.if_nameindex() not available.')
  599. def testInterfaceNameIndex(self):
  600. interfaces = socket.if_nameindex()
  601. for index, name in interfaces:
  602. self.assertIsInstance(index, int)
  603. self.assertIsInstance(name, str)
  604. # interface indices are non-zero integers
  605. self.assertGreater(index, 0)
  606. _index = socket.if_nametoindex(name)
  607. self.assertIsInstance(_index, int)
  608. self.assertEqual(index, _index)
  609. _name = socket.if_indextoname(index)
  610. self.assertIsInstance(_name, str)
  611. self.assertEqual(name, _name)
  612. @unittest.skipUnless(hasattr(socket, 'if_nameindex'),
  613. 'socket.if_nameindex() not available.')
  614. def testInvalidInterfaceNameIndex(self):
  615. # test nonexistent interface index/name
  616. self.assertRaises(socket.error, socket.if_indextoname, 0)
  617. self.assertRaises(socket.error, socket.if_nametoindex, '_DEADBEEF')
  618. # test with invalid values
  619. self.assertRaises(TypeError, socket.if_nametoindex, 0)
  620. self.assertRaises(TypeError, socket.if_indextoname, '_DEADBEEF')
  621. def testRefCountGetNameInfo(self):
  622. # Testing reference count for getnameinfo
  623. if hasattr(sys, "getrefcount"):
  624. try:
  625. # On some versions, this loses a reference
  626. orig = sys.getrefcount(__name__)
  627. socket.getnameinfo(__name__,0)
  628. except TypeError:
  629. if sys.getrefcount(__name__) != orig:
  630. self.fail("socket.getnameinfo loses a reference")
  631. def testInterpreterCrash(self):
  632. # Making sure getnameinfo doesn't crash the interpreter
  633. try:
  634. # On some versions, this crashes the interpreter.
  635. socket.getnameinfo(('x', 0, 0, 0), 0)
  636. except socket.error:
  637. pass
  638. def testNtoH(self):
  639. # This just checks that htons etc. are their own inverse,
  640. # when looking at the lower 16 or 32 bits.
  641. sizes = {socket.htonl: 32, socket.ntohl: 32,
  642. socket.htons: 16, socket.ntohs: 16}
  643. for func, size in sizes.items():
  644. mask = (1<<size) - 1
  645. for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210):
  646. self.assertEqual(i & mask, func(func(i&mask)) & mask)
  647. swapped = func(mask)
  648. self.assertEqual(swapped & mask, mask)
  649. self.assertRaises(OverflowError, func, 1<<34)
  650. def testNtoHErrors(self):
  651. good_values = [ 1, 2, 3, 1, 2, 3 ]
  652. bad_values = [ -1, -2, -3, -1, -2, -3 ]
  653. for k in good_values:
  654. socket.ntohl(k)
  655. socket.ntohs(k)
  656. socket.htonl(k)
  657. socket.htons(k)
  658. for k in bad_values:
  659. self.assertRaises(OverflowError, socket.ntohl, k)
  660. self.assertRaises(OverflowError, socket.ntohs, k)
  661. self.assertRaises(OverflowError, socket.htonl, k)
  662. self.assertRaises(OverflowError, socket.htons, k)
  663. def testGetServBy(self):
  664. eq = self.assertEqual
  665. # Find one service that exists, then check all the related interfaces.
  666. # I've ordered this by protocols that have both a tcp and udp
  667. # protocol, at least for modern Linuxes.
  668. if (sys.platform.startswith(('freebsd', 'netbsd'))
  669. or sys.platform in ('linux', 'darwin')):
  670. # avoid the 'echo' service on this platform, as there is an
  671. # assumption breaking non-standard port/protocol entry
  672. services = ('daytime', 'qotd', 'domain')
  673. else:
  674. services = ('echo', 'daytime', 'domain')
  675. for service in services:
  676. try:
  677. port = socket.getservbyname(service, 'tcp')
  678. break
  679. except socket.error:
  680. pass
  681. else:
  682. raise socket.error
  683. # Try same call with optional protocol omitted
  684. port2 = socket.getservbyname(service)
  685. eq(port, port2)
  686. # Try udp, but don't barf it it doesn't exist
  687. try:
  688. udpport = socket.getservbyname(service, 'udp')
  689. except socket.error:
  690. udpport = None
  691. else:
  692. eq(udpport, port)
  693. # Now make sure the lookup by port returns the same service name
  694. eq(socket.getservbyport(port2), service)
  695. eq(socket.getservbyport(port, 'tcp'), service)
  696. if udpport is not None:
  697. eq(socket.getservbyport(udpport, 'udp'), service)
  698. # Make sure getservbyport does not accept out of range ports.
  699. self.assertRaises(OverflowError, socket.getservbyport, -1)
  700. self.assertRaises(OverflowError, socket.getservbyport, 65536)
  701. def testDefaultTimeout(self):
  702. # Testing default timeout
  703. # The default timeout should initially be None
  704. self.assertEqual(socket.getdefaulttimeout(), None)
  705. s = socket.socket()
  706. self.assertEqual(s.gettimeout(), None)
  707. s.close()
  708. # Set the default timeout to 10, and see if it propagates
  709. socket.setdefaulttimeout(10)
  710. self.assertEqual(socket.getdefaulttimeout(), 10)
  711. s = socket.socket()
  712. self.assertEqual(s.gettimeout(), 10)
  713. s.close()
  714. # Reset the default timeout to None, and see if it propagates
  715. socket.setdefaulttimeout(None)
  716. self.assertEqual(socket.getdefaulttimeout(), None)
  717. s = socket.socket()
  718. self.assertEqual(s.gettimeout(), None)
  719. s.close()
  720. # Check that setting it to an invalid value raises ValueError
  721. self.assertRaises(ValueError, socket.setdefaulttimeout, -1)
  722. # Check that setting it to an invalid type raises TypeError
  723. self.assertRaises(TypeError, socket.setdefaulttimeout, "spam")
  724. def testIPv4_inet_aton_fourbytes(self):
  725. if not hasattr(socket, 'inet_aton'):
  726. return # No inet_aton, nothing to check
  727. # Test that issue1008086 and issue767150 are fixed.
  728. # It must return 4 bytes.
  729. self.assertEqual(b'\x00'*4, socket.inet_aton('0.0.0.0'))
  730. self.assertEqual(b'\xff'*4, socket.inet_aton('255.255.255.255'))
  731. def testIPv4toString(self):
  732. if not hasattr(socket, 'inet_pton'):
  733. return # No inet_pton() on this platform
  734. from socket import inet_aton as f, inet_pton, AF_INET
  735. g = lambda a: inet_pton(AF_INET, a)
  736. assertInvalid = lambda func,a: self.assertRaises(
  737. (socket.error, ValueError), func, a
  738. )
  739. self.assertEqual(b'\x00\x00\x00\x00', f('0.0.0.0'))
  740. self.assertEqual(b'\xff\x00\xff\x00', f('255.0.255.0'))
  741. self.assertEqual(b'\xaa\xaa\xaa\xaa', f('170.170.170.170'))
  742. self.assertEqual(b'\x01\x02\x03\x04', f('1.2.3.4'))
  743. self.assertEqual(b'\xff\xff\xff\xff', f('255.255.255.255'))
  744. assertInvalid(f, '0.0.0.')
  745. assertInvalid(f, '300.0.0.0')
  746. assertInvalid(f, 'a.0.0.0')
  747. assertInvalid(f, '1.2.3.4.5')
  748. assertInvalid(f, '::1')
  749. self.assertEqual(b'\x00\x00\x00\x00', g('0.0.0.0'))
  750. self.assertEqual(b'\xff\x00\xff\x00', g('255.0.255.0'))
  751. self.assertEqual(b'\xaa\xaa\xaa\xaa', g('170.170.170.170'))
  752. self.assertEqual(b'\xff\xff\xff\xff', g('255.255.255.255'))
  753. assertInvalid(g, '0.0.0.')
  754. assertInvalid(g, '300.0.0.0')
  755. assertInvalid(g, 'a.0.0.0')
  756. assertInvalid(g, '1.2.3.4.5')
  757. assertInvalid(g, '::1')
  758. def testIPv6toString(self):
  759. if not hasattr(socket, 'inet_pton'):
  760. return # No inet_pton() on this platform
  761. try:
  762. from socket import inet_pton, AF_INET6, has_ipv6
  763. if not has_ipv6:
  764. return
  765. except ImportError:
  766. return
  767. f = lambda a: inet_pton(AF_INET6, a)
  768. assertInvalid = lambda a: self.assertRaises(
  769. (socket.error, ValueError), f, a
  770. )
  771. self.assertEqual(b'\x00' * 16, f('::'))
  772. self.assertEqual(b'\x00' * 16, f('0::0'))
  773. self.assertEqual(b'\x00\x01' + b'\x00' * 14, f('1::'))
  774. self.assertEqual(
  775. b'\x45\xef\x76\xcb\x00\x1a\x56\xef\xaf\xeb\x0b\xac\x19\x24\xae\xae',
  776. f('45ef:76cb:1a:56ef:afeb:bac:1924:aeae')
  777. )
  778. self.assertEqual(
  779. b'\xad\x42\x0a\xbc' + b'\x00' * 4 + b'\x01\x27\x00\x00\x02\x54\x00\x02',
  780. f('ad42:abc::127:0:254:2')
  781. )
  782. self.assertEqual(b'\x00\x12\x00\x0a' + b'\x00' * 12, f('12:a::'))
  783. assertInvalid('0x20::')
  784. assertInvalid(':::')
  785. assertInvalid('::0::')
  786. assertInvalid('1::abc::')
  787. assertInvalid('1::abc::def')
  788. assertInvalid('1:2:3:4:5:6:')
  789. assertInvalid('1:2:3:4:5:6')
  790. assertInvalid('1:2:3:4:5:6:7:8:')
  791. assertInvalid('1:2:3:4:5:6:7:8:0')
  792. self.assertEqual(b'\x00' * 12 + b'\xfe\x2a\x17\x40',
  793. f('::254.42.23.64')
  794. )
  795. self.assertEqual(
  796. b'\x00\x42' + b'\x00' * 8 + b'\xa2\x9b\xfe\x2a\x17\x40',
  797. f('42::a29b:254.42.23.64')
  798. )
  799. self.assertEqual(
  800. b'\x00\x42\xa8\xb9\x00\x00\x00\x02\xff\xff\xa2\x9b\xfe\x2a\x17\x40',
  801. f('42:a8b9:0:2:ffff:a29b:254.42.23.64')
  802. )
  803. assertInvalid('255.254.253.252')
  804. assertInvalid('1::260.2.3.0')
  805. assertInvalid('1::0.be.e.0')
  806. assertInvalid('1:2:3:4:5:6:7:1.2.3.4')
  807. assertInvalid('::1.2.3.4:0')
  808. assertInvalid('0.100.200.0:3:4:5:6:7:8')
  809. def testStringToIPv4(self):
  810. if not hasattr(socket, 'inet_ntop'):
  811. return # No inet_ntop() on this platform
  812. from socket import inet_ntoa as f, inet_ntop, AF_INET
  813. g = lambda a: inet_ntop(AF_INET, a)
  814. assertInvalid = lambda func,a: self.assertRaises(
  815. (socket.error, ValueError), func, a
  816. )
  817. self.assertEqual('1.0.1.0', f(b'\x01\x00\x01\x00'))
  818. self.assertEqual('170.85.170.85', f(b'\xaa\x55\xaa\x55'))
  819. self.assertEqual('255.255.255.255', f(b'\xff\xff\xff\xff'))
  820. self.assertEqual('1.2.3.4', f(b'\x01\x02\x03\x04'))
  821. assertInvalid(f, b'\x00' * 3)
  822. assertInvalid(f, b'\x00' * 5)
  823. assertInvalid(f, b'\x00' * 16)
  824. self.assertEqual('1.0.1.0', g(b'\x01\x00\x01\x00'))
  825. self.assertEqual('170.85.170.85', g(b'\xaa\x55\xaa\x55'))
  826. self.assertEqual('255.255.255.255', g(b'\xff\xff\xff\xff'))
  827. assertInvalid(g, b'\x00' * 3)
  828. assertInvalid(g, b'\x00' * 5)
  829. assertInvalid(g, b'\x00' * 16)
  830. def testStringToIPv6(self):
  831. if not hasattr(socket, 'inet_ntop'):
  832. return # No inet_ntop() on this platform
  833. try:
  834. from socket import inet_ntop, AF_INET6, has_ipv6
  835. if not has_ipv6:
  836. return
  837. except ImportError:
  838. return
  839. f = lambda a: inet_ntop(AF_INET6, a)
  840. assertInvalid = lambda a: self.assertRaises(
  841. (socket.error, ValueError), f, a
  842. )
  843. self.assertEqual('::', f(b'\x00' * 16))
  844. self.assertEqual('::1', f(b'\x00' * 15 + b'\x01'))
  845. self.assertEqual(
  846. 'aef:b01:506:1001:ffff:9997:55:170',
  847. f(b'\x0a\xef\x0b\x01\x05\x06\x10\x01\xff\xff\x99\x97\x00\x55\x01\x70')
  848. )
  849. assertInvalid(b'\x12' * 15)
  850. assertInvalid(b'\x12' * 17)
  851. assertInvalid(b'\x12' * 4)
  852. # XXX The following don't test module-level functionality...
  853. def testSockName(self):
  854. # Testing getsockname()
  855. port = support.find_unused_port()
  856. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  857. self.addCleanup(sock.close)
  858. sock.bind(("0.0.0.0", port))
  859. name = sock.getsockname()
  860. # XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate
  861. # it reasonable to get the host's addr in addition to 0.0.0.0.
  862. # At least for eCos. This is required for the S/390 to pass.
  863. try:
  864. my_ip_addr = socket.gethostbyname(socket.gethostname())
  865. except socket.error:
  866. # Probably name lookup wasn't set up right; skip this test
  867. return
  868. self.assertIn(name[0], ("0.0.0.0", my_ip_addr), '%s invalid' % name[0])
  869. self.assertEqual(name[1], port)
  870. def testGetSockOpt(self):
  871. # Testing getsockopt()
  872. # We know a socket should start without reuse==0
  873. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  874. self.addCleanup(sock.close)
  875. reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
  876. self.assertFalse(reuse != 0, "initial mode is reuse")
  877. def testSetSockOpt(self):
  878. # Testing setsockopt()
  879. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  880. self.addCleanup(sock.close)
  881. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  882. reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
  883. self.assertFalse(reuse == 0, "failed to set reuse mode")
  884. def testSendAfterClose(self):
  885. # testing send() after close() with timeout
  886. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  887. sock.settimeout(1)
  888. sock.close()
  889. self.assertRaises(socket.error, sock.send, b"spam")
  890. def testNewAttributes(self):
  891. # testing .family, .type and .protocol
  892. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  893. self.assertEqual(sock.family, socket.AF_INET)
  894. self.assertEqual(sock.type, socket.SOCK_STREAM)
  895. self.assertEqual(sock.proto, 0)
  896. sock.close()
  897. def test_getsockaddrarg(self):
  898. host = '0.0.0.0'
  899. port = support.find_unused_port()
  900. big_port = port + 65536
  901. neg_port = port - 65536
  902. sock = socket.socket()
  903. try:
  904. self.assertRaises(OverflowError, sock.bind, (host, big_port))
  905. self.assertRaises(OverflowError, sock.bind, (host, neg_port))
  906. sock.bind((host, port))
  907. finally:
  908. sock.close()
  909. @unittest.skipUnless(os.name == "nt", "Windows specific")
  910. def test_sock_ioctl(self):
  911. self.assertTrue(hasattr(socket.socket, 'ioctl'))
  912. self.assertTrue(hasattr(socket, 'SIO_RCVALL'))
  913. self.assertTrue(hasattr(socket, 'RCVALL_ON'))
  914. self.assertTrue(hasattr(socket, 'RCVALL_OFF'))
  915. self.assertTrue(hasattr(socket, 'SIO_KEEPALIVE_VALS'))
  916. s = socket.socket()
  917. self.addCleanup(s.close)
  918. self.assertRaises(ValueError, s.ioctl, -1, None)
  919. s.ioctl(socket.SIO_KEEPALIVE_VALS, (1, 100, 100))
  920. def testGetaddrinfo(self):
  921. try:
  922. socket.getaddrinfo('localhost', 80)
  923. except socket.gaierror as err:
  924. if err.errno == socket.EAI_SERVICE:
  925. # see http://bugs.python.org/issue1282647
  926. self.skipTest("buggy libc version")
  927. raise
  928. # len of every sequence is supposed to be == 5
  929. for info in socket.getaddrinfo(HOST, None):
  930. self.assertEqual(len(info), 5)
  931. # host can be a domain name, a string representation of an
  932. # IPv4/v6 address or None
  933. socket.getaddrinfo('localhost', 80)
  934. socket.getaddrinfo('127.0.0.1', 80)
  935. socket.getaddrinfo(None, 80)
  936. if support.IPV6_ENABLED:
  937. socket.getaddrinfo('::1', 80)
  938. # port can be a string service name such as "http", a numeric
  939. # port number or None
  940. socket.getaddrinfo(HOST, "http")
  941. socket.getaddrinfo(HOST, 80)
  942. socket.getaddrinfo(HOST, None)
  943. # test family and socktype filters
  944. infos = socket.getaddrinfo(HOST, None, socket.AF_INET)
  945. for family, _, _, _, _ in infos:
  946. self.assertEqual(family, socket.AF_INET)
  947. infos = socket.getaddrinfo(HOST, None, 0, socket.SOCK_STREAM)
  948. for _, socktype, _, _, _ in infos:
  949. self.assertEqual(socktype, socket.SOCK_STREAM)
  950. # test proto and flags arguments
  951. socket.getaddrinfo(HOST, None, 0, 0, socket.SOL_TCP)
  952. socket.getaddrinfo(HOST, None, 0, 0, 0, socket.AI_PASSIVE)
  953. # a server willing to support both IPv4 and IPv6 will
  954. # usually do this
  955. socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
  956. socket.AI_PASSIVE)
  957. # test keyword arguments
  958. a = socket.getaddrinfo(HOST, None)
  959. b = socket.getaddrinfo(host=HOST, port=None)
  960. self.assertEqual(a, b)
  961. a = socket.getaddrinfo(HOST, None, socket.AF_INET)
  962. b = socket.getaddrinfo(HOST, None, family=socket.AF_INET)
  963. self.assertEqual(a, b)
  964. a = socket.getaddrinfo(HOST, None, 0, socket.SOCK_STREAM)
  965. b = socket.getaddrinfo(HOST, None, type=socket.SOCK_STREAM)
  966. self.assertEqual(a, b)
  967. a = socket.getaddrinfo(HOST, None, 0, 0, socket.SOL_TCP)
  968. b = socket.getaddrinfo(HOST, None, proto=socket.SOL_TCP)
  969. self.assertEqual(a, b)
  970. a = socket.getaddrinfo(HOST, None, 0, 0, 0, socket.AI_PASSIVE)
  971. b = socket.getaddrinfo(HOST, None, flags=socket.AI_PASSIVE)
  972. self.assertEqual(a, b)
  973. a = socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
  974. socket.AI_PASSIVE)
  975. b = socket.getaddrinfo(host=None, port=0, family=socket.AF_UNSPEC,
  976. type=socket.SOCK_STREAM, proto=0,
  977. flags=socket.AI_PASSIVE)
  978. self.assertEqual(a, b)
  979. # Issue #6697.
  980. self.assertRaises(UnicodeEncodeError, socket.getaddrinfo, 'localhost', '\uD800')
  981. def test_getnameinfo(self):
  982. # only IP addresses are allowed
  983. self.assertRaises(socket.error, socket.getnameinfo, ('mail.python.org',0), 0)
  984. @unittest.skipUnless(support.is_resource_enabled('network'),
  985. 'network is not enabled')
  986. def test_idna(self):
  987. # Check for internet access before running test (issue #12804).
  988. try:
  989. socket.gethostbyname('python.org')
  990. except socket.gaierror as e:
  991. if e.errno == socket.EAI_NODATA:
  992. self.skipTest('internet access required for this test')
  993. # these should all be successful
  994. socket.gethostbyname('испытание.python.org')
  995. socket.gethostbyname_ex('испытание.python.org')
  996. socket.getaddrinfo('испытание.python.org',0,socket.AF_UNSPEC,socket.SOCK_STREAM)
  997. # this may not work if the forward lookup choses the IPv6 address, as that doesn't
  998. # have a reverse entry yet
  999. # socket.gethostbyaddr('испытание.python.org')
  1000. def check_sendall_interrupted(self, with_timeout):
  1001. # socketpair() is not stricly required, but it makes things easier.
  1002. if not hasattr(signal, 'alarm') or not hasattr(socket, 'socketpair'):
  1003. self.skipTest("signal.alarm and socket.socketpair required for this test")
  1004. # Our signal handlers clobber the C errno by calling a math function
  1005. # with an invalid domain value.
  1006. def ok_handler(*args):
  1007. self.assertRaises(ValueError, math.acosh, 0)
  1008. def raising_handler(*args):
  1009. self.assertRaises(ValueError, math.acosh, 0)
  1010. 1 // 0
  1011. c, s = socket.socketpair()
  1012. old_alarm = signal.signal(signal.SIGALRM, raising_handler)
  1013. try:
  1014. if with_timeout:
  1015. # Just above the one second minimum for signal.alarm
  1016. c.settimeout(1.5)
  1017. with self.assertRaises(ZeroDivisionError):
  1018. signal.alarm(1)
  1019. c.sendall(b"x" * (1024**2))
  1020. if with_timeout:
  1021. signal.signal(signal.SIGALRM, ok_handler)
  1022. signal.alarm(1)
  1023. self.assertRaises(socket.timeout, c.sendall, b"x" * (1024**2))
  1024. finally:
  1025. signal.signal(signal.SIGALRM, old_alarm)
  1026. c.close()
  1027. s.close()
  1028. def test_sendall_interrupted(self):
  1029. self.check_sendall_interrupted(False)
  1030. def test_sendall_interrupted_with_timeout(self):
  1031. self.check_sendall_interrupted(True)
  1032. def test_dealloc_warn(self):
  1033. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  1034. r = repr(sock)
  1035. with self.assertWarns(ResourceWarning) as cm:
  1036. sock = None
  1037. support.gc_collect()
  1038. self.assertIn(r, str(cm.warning.args[0]))
  1039. # An open socket file object gets dereferenced after the socket
  1040. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  1041. f = sock.makefile('rb')
  1042. r = repr(sock)
  1043. sock = None
  1044. support.gc_collect()
  1045. with self.assertWarns(ResourceWarning):
  1046. f = None
  1047. support.gc_collect()
  1048. def test_name_closed_socketio(self):
  1049. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
  1050. fp = sock.makefile("rb")
  1051. fp.close()
  1052. self.assertEqual(repr(fp), "<_io.BufferedReader name=-1>")
  1053. def test_pickle(self):
  1054. sock = socket.socket()
  1055. with sock:
  1056. for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
  1057. self.assertRaises(TypeError, pickle.dumps, sock, protocol)
  1058. def test_listen_backlog0(self):
  1059. srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  1060. srv.bind((HOST, 0))
  1061. # backlog = 0
  1062. srv.listen(0)
  1063. srv.close()
  1064. @unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 required for this test.')
  1065. def test_flowinfo(self):
  1066. self.assertRaises(OverflowError, socket.getnameinfo,
  1067. ('::1',0, 0xffffffff), 0)
  1068. with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s:
  1069. self.assertRaises(OverflowError, s.bind, ('::1', 0, -10))
  1070. @unittest.skipUnless(HAVE_SOCKET_CAN, 'SocketCan required for this test.')
  1071. class BasicCANTest(unittest.TestCase):
  1072. def testCrucialConstants(self):
  1073. socket.AF_CAN
  1074. socket.PF_CAN
  1075. socket.CAN_RAW
  1076. def testCreateSocket(self):
  1077. with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
  1078. pass
  1079. def testBindAny(self):
  1080. with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
  1081. s.bind(('', ))
  1082. def testTooLongInterfaceName(self):
  1083. # most systems limit IFNAMSIZ to 16, take 1024 to be sure
  1084. with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
  1085. self.assertRaisesRegex(socket.error, 'interface name too long',
  1086. s.bind, ('x' * 1024,))
  1087. @unittest.skipUnless(hasattr(socket, "CAN_RAW_LOOPBACK"),
  1088. 'socket.CAN_RAW_LOOPBACK required for this test.')
  1089. def testLoopback(self):
  1090. with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
  1091. for loopback in (0, 1):
  1092. s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_LOOPBACK,
  1093. loopback)
  1094. self.assertEqual(loopback,
  1095. s.getsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_LOOPBACK))
  1096. @unittest.skipUnless(hasattr(socket, "CAN_RAW_FILTER"),
  1097. 'socket.CAN_RAW_FILTER required for this test.')
  1098. def testFilter(self):
  1099. can_id, can_mask = 0x200, 0x700
  1100. can_filter = struct.pack("=II", can_id, can_mask)
  1101. with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
  1102. s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FILTER, can_filter)
  1103. self.assertEqual(can_filter,
  1104. s.getsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FILTER, 8))
  1105. @unittest.skipUnless(HAVE_SOCKET_CAN, 'SocketCan required for this test.')
  1106. @unittest.skipUnless(thread, 'Threading required for this test.')
  1107. class CANTest(ThreadedCANSocketTest):
  1108. """The CAN frame structure is defined in <linux/can.h>:
  1109. struct can_frame {
  1110. canid_t can_id; /* 32 bit CAN_ID + EFF/RTR/ERR flags */
  1111. __u8 can_dlc; /* data length code: 0 .. 8 */
  1112. __u8 data[8] __attribute__((aligned(8)));
  1113. };
  1114. """
  1115. can_frame_fmt = "=IB3x8s"
  1116. def __init__(self, methodName='runTest'):
  1117. ThreadedCANSocketTest.__init__(self, methodName=methodName)
  1118. @classmethod
  1119. def build_can_frame(cls, can_id, data):
  1120. """Build a CAN frame."""
  1121. can_dlc = len(data)
  1122. data = data.ljust(8, b'\x00')
  1123. return struct.pack(cls.can_frame_fmt, can_id, can_dlc, data)
  1124. @classmethod
  1125. def dissect_can_frame(cls, frame):
  1126. """Dissect a CAN frame."""
  1127. can_id, can_dlc, data = struct.unpack(cls.can_frame_fmt, frame)
  1128. return (can_id, can_dlc, data[:can_dlc])
  1129. def testSendFrame(self):
  1130. cf, addr = self.s.recvfrom(self.bufsize)
  1131. self.assertEqual(self.cf, cf)
  1132. self.assertEqual(addr[0], self.interface)
  1133. self.assertEqual(addr[1], socket.AF_CAN)
  1134. def _testSendFrame(self):
  1135. self.cf = self.build_can_frame(0x00, b'\x01\x02\x03\x04\x05')
  1136. self.cli.send(self.cf)
  1137. def testSendMaxFrame(self):
  1138. cf, addr = self.s.recvfrom(self.bufsize)
  1139. self.assertEqual(self.cf, cf)
  1140. def _testSendMaxFrame(self):
  1141. self.cf = self.build_can_frame(0x00, b'\x07' * 8)
  1142. self.cli.send(self.cf)
  1143. def testSendMultiFrames(self):
  1144. cf, addr = self.s.recvfrom(self.bufsize)
  1145. self.assertEqual(self.cf1, cf)
  1146. cf, addr = self.s.recvfrom(self.bufsize)
  1147. self.assertEqual(self.cf2, cf)
  1148. def _testSendMultiFrames(self):
  1149. self.cf1 = self.build_can_frame(0x07, b'\x44\x33\x22\x11')
  1150. self.cli.send(self.cf1)
  1151. self.cf2 = self.build_can_frame(0x12, b'\x99\x22\x33')
  1152. self.cli.send(self.cf2)
  1153. @unittest.skipUnless(HAVE_SOCKET_RDS, 'RDS sockets required for this test.')
  1154. class BasicRDSTest(unittest.TestCase):
  1155. def testCrucialConstants(self):
  1156. socket.AF_RDS
  1157. socket.PF_RDS
  1158. def testCreateSocket(self):
  1159. with socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0) as s:
  1160. pass
  1161. def testSocketBufferSize(self):
  1162. bufsize = 16384
  1163. with socket.socket(socket.PF_RDS, socket.SOCK_SEQPACKET, 0) as s:
  1164. s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, bufsize)
  1165. s.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, bufsize)
  1166. @unittest.skipUnless(HAVE_SOCKET_RDS, 'RDS sockets required for this test.')
  1167. @unittest.skipUnless(thread, 'Threading required for this test.')
  1168. class RDSTest(ThreadedRDSSocketTest):
  1169. def __init__(self, methodName='runT…

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