PageRenderTime 191ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 1ms

/Lib/test/test_socket.py

https://bitbucket.org/atsuoishimoto/cpython
Python | 5106 lines | 4716 code | 195 blank | 195 comment | 53 complexity | 8e8c39db65f88ba87ee1f97f7446911d MD5 | raw file
Possible License(s): 0BSD

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

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

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