PageRenderTime 75ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 1ms

/Lib/test/test_socket.py

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

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