PageRenderTime 121ms CodeModel.GetById 26ms app.highlight 77ms RepoModel.GetById 1ms app.codeStats 1ms

/Lib/test/test_socket.py

https://bitbucket.org/akruis/fg2python
Python | 5093 lines | 4701 code | 196 blank | 196 comment | 48 complexity | e1ed2f3ad622a4c0b77e5c70519dc8ee MD5 | raw file

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

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

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