PageRenderTime 31ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 0ms

/Lib/test/test_socket.py

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

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