PageRenderTime 29ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 1ms

/Lib/test/test_socket.py

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

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