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

/Lib/test/test_socket.py

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

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