PageRenderTime 77ms CodeModel.GetById 31ms RepoModel.GetById 1ms app.codeStats 1ms

/Lib/test/test_socket.py

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

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