PageRenderTime 10ms CodeModel.GetById 5ms app.highlight 69ms RepoModel.GetById 0ms app.codeStats 1ms

/Lib/test/test_socket.py

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

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