PageRenderTime 98ms CodeModel.GetById 6ms app.highlight 74ms RepoModel.GetById 1ms app.codeStats 1ms

/Lib/test/test_socket.py

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

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