PageRenderTime 93ms CodeModel.GetById 6ms app.highlight 70ms RepoModel.GetById 1ms app.codeStats 1ms

/Lib/test/test_socket.py

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

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