PageRenderTime 123ms CodeModel.GetById 5ms app.highlight 100ms RepoModel.GetById 1ms app.codeStats 1ms

/Lib/test/test_socket.py

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

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