PageRenderTime 8ms CodeModel.GetById 5ms app.highlight 79ms RepoModel.GetById 1ms app.codeStats 0ms

/policy-and-header-refactor/Lib/test/test_socket.py

https://bitbucket.org/l0nwlf/policy-and-header-refactor
Python | 1494 lines | 1320 code | 93 blank | 81 comment | 47 complexity | ee7c37a0587e75be1c7602442c7083c8 MD5 | raw file

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

   1#!/usr/bin/env python3
   2
   3import unittest
   4from test import support
   5
   6import errno
   7import io
   8import socket
   9import select
  10import time
  11import traceback
  12import queue
  13import sys
  14import os
  15import array
  16from weakref import proxy
  17import signal
  18
  19HOST = support.HOST
  20MSG = b'Michael Gilfix was here\n'
  21
  22try:
  23    import _thread as thread
  24    import threading
  25except ImportError:
  26    thread = None
  27    threading = None
  28
  29class SocketTCPTest(unittest.TestCase):
  30
  31    def setUp(self):
  32        self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  33        self.port = support.bind_port(self.serv)
  34        self.serv.listen(1)
  35
  36    def tearDown(self):
  37        self.serv.close()
  38        self.serv = None
  39
  40class SocketUDPTest(unittest.TestCase):
  41
  42    def setUp(self):
  43        self.serv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  44        self.port = support.bind_port(self.serv)
  45
  46    def tearDown(self):
  47        self.serv.close()
  48        self.serv = None
  49
  50class ThreadableTest:
  51    """Threadable Test class
  52
  53    The ThreadableTest class makes it easy to create a threaded
  54    client/server pair from an existing unit test. To create a
  55    new threaded class from an existing unit test, use multiple
  56    inheritance:
  57
  58        class NewClass (OldClass, ThreadableTest):
  59            pass
  60
  61    This class defines two new fixture functions with obvious
  62    purposes for overriding:
  63
  64        clientSetUp ()
  65        clientTearDown ()
  66
  67    Any new test functions within the class must then define
  68    tests in pairs, where the test name is preceeded with a
  69    '_' to indicate the client portion of the test. Ex:
  70
  71        def testFoo(self):
  72            # Server portion
  73
  74        def _testFoo(self):
  75            # Client portion
  76
  77    Any exceptions raised by the clients during their tests
  78    are caught and transferred to the main thread to alert
  79    the testing framework.
  80
  81    Note, the server setup function cannot call any blocking
  82    functions that rely on the client thread during setup,
  83    unless serverExplicitReady() is called just before
  84    the blocking call (such as in setting up a client/server
  85    connection and performing the accept() in setUp().
  86    """
  87
  88    def __init__(self):
  89        # Swap the true setup function
  90        self.__setUp = self.setUp
  91        self.__tearDown = self.tearDown
  92        self.setUp = self._setUp
  93        self.tearDown = self._tearDown
  94
  95    def serverExplicitReady(self):
  96        """This method allows the server to explicitly indicate that
  97        it wants the client thread to proceed. This is useful if the
  98        server is about to execute a blocking routine that is
  99        dependent upon the client thread during its setup routine."""
 100        self.server_ready.set()
 101
 102    def _setUp(self):
 103        self.server_ready = threading.Event()
 104        self.client_ready = threading.Event()
 105        self.done = threading.Event()
 106        self.queue = queue.Queue(1)
 107
 108        # Do some munging to start the client test.
 109        methodname = self.id()
 110        i = methodname.rfind('.')
 111        methodname = methodname[i+1:]
 112        test_method = getattr(self, '_' + methodname)
 113        self.client_thread = thread.start_new_thread(
 114            self.clientRun, (test_method,))
 115
 116        self.__setUp()
 117        if not self.server_ready.is_set():
 118            self.server_ready.set()
 119        self.client_ready.wait()
 120
 121    def _tearDown(self):
 122        self.__tearDown()
 123        self.done.wait()
 124
 125        if self.queue.qsize():
 126            msg = self.queue.get()
 127            self.fail(msg)
 128
 129    def clientRun(self, test_func):
 130        self.server_ready.wait()
 131        self.client_ready.set()
 132        self.clientSetUp()
 133        if not hasattr(test_func, '__call__'):
 134            raise TypeError("test_func must be a callable function")
 135        try:
 136            test_func()
 137        except Exception as strerror:
 138            self.queue.put(strerror)
 139        self.clientTearDown()
 140
 141    def clientSetUp(self):
 142        raise NotImplementedError("clientSetUp must be implemented.")
 143
 144    def clientTearDown(self):
 145        self.done.set()
 146        thread.exit()
 147
 148class ThreadedTCPSocketTest(SocketTCPTest, ThreadableTest):
 149
 150    def __init__(self, methodName='runTest'):
 151        SocketTCPTest.__init__(self, methodName=methodName)
 152        ThreadableTest.__init__(self)
 153
 154    def clientSetUp(self):
 155        self.cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 156
 157    def clientTearDown(self):
 158        self.cli.close()
 159        self.cli = None
 160        ThreadableTest.clientTearDown(self)
 161
 162class ThreadedUDPSocketTest(SocketUDPTest, ThreadableTest):
 163
 164    def __init__(self, methodName='runTest'):
 165        SocketUDPTest.__init__(self, methodName=methodName)
 166        ThreadableTest.__init__(self)
 167
 168    def clientSetUp(self):
 169        self.cli = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
 170
 171class SocketConnectedTest(ThreadedTCPSocketTest):
 172    """Socket tests for client-server connection.
 173
 174    self.cli_conn is a client socket connected to the server.  The
 175    setUp() method guarantees that it is connected to the server.
 176    """
 177
 178    def __init__(self, methodName='runTest'):
 179        ThreadedTCPSocketTest.__init__(self, methodName=methodName)
 180
 181    def setUp(self):
 182        ThreadedTCPSocketTest.setUp(self)
 183        # Indicate explicitly we're ready for the client thread to
 184        # proceed and then perform the blocking call to accept
 185        self.serverExplicitReady()
 186        conn, addr = self.serv.accept()
 187        self.cli_conn = conn
 188
 189    def tearDown(self):
 190        self.cli_conn.close()
 191        self.cli_conn = None
 192        ThreadedTCPSocketTest.tearDown(self)
 193
 194    def clientSetUp(self):
 195        ThreadedTCPSocketTest.clientSetUp(self)
 196        self.cli.connect((HOST, self.port))
 197        self.serv_conn = self.cli
 198
 199    def clientTearDown(self):
 200        self.serv_conn.close()
 201        self.serv_conn = None
 202        ThreadedTCPSocketTest.clientTearDown(self)
 203
 204class SocketPairTest(unittest.TestCase, ThreadableTest):
 205
 206    def __init__(self, methodName='runTest'):
 207        unittest.TestCase.__init__(self, methodName=methodName)
 208        ThreadableTest.__init__(self)
 209
 210    def setUp(self):
 211        self.serv, self.cli = socket.socketpair()
 212
 213    def tearDown(self):
 214        self.serv.close()
 215        self.serv = None
 216
 217    def clientSetUp(self):
 218        pass
 219
 220    def clientTearDown(self):
 221        self.cli.close()
 222        self.cli = None
 223        ThreadableTest.clientTearDown(self)
 224
 225
 226#######################################################################
 227## Begin Tests
 228
 229class GeneralModuleTests(unittest.TestCase):
 230
 231    def test_repr(self):
 232        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 233        self.assertTrue(repr(s).startswith("<socket.socket object"))
 234
 235    def test_weakref(self):
 236        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 237        p = proxy(s)
 238        self.assertEqual(p.fileno(), s.fileno())
 239        s.close()
 240        s = None
 241        try:
 242            p.fileno()
 243        except ReferenceError:
 244            pass
 245        else:
 246            self.fail('Socket proxy still exists')
 247
 248    def testSocketError(self):
 249        # Testing socket module exceptions
 250        def raise_error(*args, **kwargs):
 251            raise socket.error
 252        def raise_herror(*args, **kwargs):
 253            raise socket.herror
 254        def raise_gaierror(*args, **kwargs):
 255            raise socket.gaierror
 256        self.assertRaises(socket.error, raise_error,
 257                              "Error raising socket exception.")
 258        self.assertRaises(socket.error, raise_herror,
 259                              "Error raising socket exception.")
 260        self.assertRaises(socket.error, raise_gaierror,
 261                              "Error raising socket exception.")
 262
 263    def testCrucialConstants(self):
 264        # Testing for mission critical constants
 265        socket.AF_INET
 266        socket.SOCK_STREAM
 267        socket.SOCK_DGRAM
 268        socket.SOCK_RAW
 269        socket.SOCK_RDM
 270        socket.SOCK_SEQPACKET
 271        socket.SOL_SOCKET
 272        socket.SO_REUSEADDR
 273
 274    def testHostnameRes(self):
 275        # Testing hostname resolution mechanisms
 276        hostname = socket.gethostname()
 277        try:
 278            ip = socket.gethostbyname(hostname)
 279        except socket.error:
 280            # Probably name lookup wasn't set up right; skip this test
 281            return
 282        self.assertTrue(ip.find('.') >= 0, "Error resolving host to ip.")
 283        try:
 284            hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
 285        except socket.error:
 286            # Probably a similar problem as above; skip this test
 287            return
 288        all_host_names = [hostname, hname] + aliases
 289        fqhn = socket.getfqdn(ip)
 290        if not fqhn in all_host_names:
 291            self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names)))
 292
 293    def testRefCountGetNameInfo(self):
 294        # Testing reference count for getnameinfo
 295        if hasattr(sys, "getrefcount"):
 296            try:
 297                # On some versions, this loses a reference
 298                orig = sys.getrefcount(__name__)
 299                socket.getnameinfo(__name__,0)
 300            except TypeError:
 301                if sys.getrefcount(__name__) != orig:
 302                    self.fail("socket.getnameinfo loses a reference")
 303
 304    def testInterpreterCrash(self):
 305        # Making sure getnameinfo doesn't crash the interpreter
 306        try:
 307            # On some versions, this crashes the interpreter.
 308            socket.getnameinfo(('x', 0, 0, 0), 0)
 309        except socket.error:
 310            pass
 311
 312    def testNtoH(self):
 313        # This just checks that htons etc. are their own inverse,
 314        # when looking at the lower 16 or 32 bits.
 315        sizes = {socket.htonl: 32, socket.ntohl: 32,
 316                 socket.htons: 16, socket.ntohs: 16}
 317        for func, size in sizes.items():
 318            mask = (1<<size) - 1
 319            for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210):
 320                self.assertEqual(i & mask, func(func(i&mask)) & mask)
 321
 322            swapped = func(mask)
 323            self.assertEqual(swapped & mask, mask)
 324            self.assertRaises(OverflowError, func, 1<<34)
 325
 326    def testNtoHErrors(self):
 327        good_values = [ 1, 2, 3, 1, 2, 3 ]
 328        bad_values = [ -1, -2, -3, -1, -2, -3 ]
 329        for k in good_values:
 330            socket.ntohl(k)
 331            socket.ntohs(k)
 332            socket.htonl(k)
 333            socket.htons(k)
 334        for k in bad_values:
 335            self.assertRaises(OverflowError, socket.ntohl, k)
 336            self.assertRaises(OverflowError, socket.ntohs, k)
 337            self.assertRaises(OverflowError, socket.htonl, k)
 338            self.assertRaises(OverflowError, socket.htons, k)
 339
 340    def testGetServBy(self):
 341        eq = self.assertEqual
 342        # Find one service that exists, then check all the related interfaces.
 343        # I've ordered this by protocols that have both a tcp and udp
 344        # protocol, at least for modern Linuxes.
 345        if sys.platform in ('linux2', 'freebsd4', 'freebsd5', 'freebsd6',
 346                            'freebsd7', 'freebsd8', 'darwin'):
 347            # avoid the 'echo' service on this platform, as there is an
 348            # assumption breaking non-standard port/protocol entry
 349            services = ('daytime', 'qotd', 'domain')
 350        else:
 351            services = ('echo', 'daytime', 'domain')
 352        for service in services:
 353            try:
 354                port = socket.getservbyname(service, 'tcp')
 355                break
 356            except socket.error:
 357                pass
 358        else:
 359            raise socket.error
 360        # Try same call with optional protocol omitted
 361        port2 = socket.getservbyname(service)
 362        eq(port, port2)
 363        # Try udp, but don't barf it it doesn't exist
 364        try:
 365            udpport = socket.getservbyname(service, 'udp')
 366        except socket.error:
 367            udpport = None
 368        else:
 369            eq(udpport, port)
 370        # Now make sure the lookup by port returns the same service name
 371        eq(socket.getservbyport(port2), service)
 372        eq(socket.getservbyport(port, 'tcp'), service)
 373        if udpport is not None:
 374            eq(socket.getservbyport(udpport, 'udp'), service)
 375        # Make sure getservbyport does not accept out of range ports.
 376        self.assertRaises(OverflowError, socket.getservbyport, -1)
 377        self.assertRaises(OverflowError, socket.getservbyport, 65536)
 378
 379    def testDefaultTimeout(self):
 380        # Testing default timeout
 381        # The default timeout should initially be None
 382        self.assertEqual(socket.getdefaulttimeout(), None)
 383        s = socket.socket()
 384        self.assertEqual(s.gettimeout(), None)
 385        s.close()
 386
 387        # Set the default timeout to 10, and see if it propagates
 388        socket.setdefaulttimeout(10)
 389        self.assertEqual(socket.getdefaulttimeout(), 10)
 390        s = socket.socket()
 391        self.assertEqual(s.gettimeout(), 10)
 392        s.close()
 393
 394        # Reset the default timeout to None, and see if it propagates
 395        socket.setdefaulttimeout(None)
 396        self.assertEqual(socket.getdefaulttimeout(), None)
 397        s = socket.socket()
 398        self.assertEqual(s.gettimeout(), None)
 399        s.close()
 400
 401        # Check that setting it to an invalid value raises ValueError
 402        self.assertRaises(ValueError, socket.setdefaulttimeout, -1)
 403
 404        # Check that setting it to an invalid type raises TypeError
 405        self.assertRaises(TypeError, socket.setdefaulttimeout, "spam")
 406
 407    def testIPv4_inet_aton_fourbytes(self):
 408        if not hasattr(socket, 'inet_aton'):
 409            return  # No inet_aton, nothing to check
 410        # Test that issue1008086 and issue767150 are fixed.
 411        # It must return 4 bytes.
 412        self.assertEquals(b'\x00'*4, socket.inet_aton('0.0.0.0'))
 413        self.assertEquals(b'\xff'*4, socket.inet_aton('255.255.255.255'))
 414
 415    def testIPv4toString(self):
 416        if not hasattr(socket, 'inet_pton'):
 417            return # No inet_pton() on this platform
 418        from socket import inet_aton as f, inet_pton, AF_INET
 419        g = lambda a: inet_pton(AF_INET, a)
 420
 421        self.assertEquals(b'\x00\x00\x00\x00', f('0.0.0.0'))
 422        self.assertEquals(b'\xff\x00\xff\x00', f('255.0.255.0'))
 423        self.assertEquals(b'\xaa\xaa\xaa\xaa', f('170.170.170.170'))
 424        self.assertEquals(b'\x01\x02\x03\x04', f('1.2.3.4'))
 425        self.assertEquals(b'\xff\xff\xff\xff', f('255.255.255.255'))
 426
 427        self.assertEquals(b'\x00\x00\x00\x00', g('0.0.0.0'))
 428        self.assertEquals(b'\xff\x00\xff\x00', g('255.0.255.0'))
 429        self.assertEquals(b'\xaa\xaa\xaa\xaa', g('170.170.170.170'))
 430        self.assertEquals(b'\xff\xff\xff\xff', g('255.255.255.255'))
 431
 432    def testIPv6toString(self):
 433        if not hasattr(socket, 'inet_pton'):
 434            return # No inet_pton() on this platform
 435        try:
 436            from socket import inet_pton, AF_INET6, has_ipv6
 437            if not has_ipv6:
 438                return
 439        except ImportError:
 440            return
 441        f = lambda a: inet_pton(AF_INET6, a)
 442
 443        self.assertEquals(b'\x00' * 16, f('::'))
 444        self.assertEquals(b'\x00' * 16, f('0::0'))
 445        self.assertEquals(b'\x00\x01' + b'\x00' * 14, f('1::'))
 446        self.assertEquals(
 447            b'\x45\xef\x76\xcb\x00\x1a\x56\xef\xaf\xeb\x0b\xac\x19\x24\xae\xae',
 448            f('45ef:76cb:1a:56ef:afeb:bac:1924:aeae')
 449        )
 450
 451    def testStringToIPv4(self):
 452        if not hasattr(socket, 'inet_ntop'):
 453            return # No inet_ntop() on this platform
 454        from socket import inet_ntoa as f, inet_ntop, AF_INET
 455        g = lambda a: inet_ntop(AF_INET, a)
 456
 457        self.assertEquals('1.0.1.0', f(b'\x01\x00\x01\x00'))
 458        self.assertEquals('170.85.170.85', f(b'\xaa\x55\xaa\x55'))
 459        self.assertEquals('255.255.255.255', f(b'\xff\xff\xff\xff'))
 460        self.assertEquals('1.2.3.4', f(b'\x01\x02\x03\x04'))
 461
 462        self.assertEquals('1.0.1.0', g(b'\x01\x00\x01\x00'))
 463        self.assertEquals('170.85.170.85', g(b'\xaa\x55\xaa\x55'))
 464        self.assertEquals('255.255.255.255', g(b'\xff\xff\xff\xff'))
 465
 466    def testStringToIPv6(self):
 467        if not hasattr(socket, 'inet_ntop'):
 468            return # No inet_ntop() on this platform
 469        try:
 470            from socket import inet_ntop, AF_INET6, has_ipv6
 471            if not has_ipv6:
 472                return
 473        except ImportError:
 474            return
 475        f = lambda a: inet_ntop(AF_INET6, a)
 476
 477        self.assertEquals('::', f(b'\x00' * 16))
 478        self.assertEquals('::1', f(b'\x00' * 15 + b'\x01'))
 479        self.assertEquals(
 480            'aef:b01:506:1001:ffff:9997:55:170',
 481            f(b'\x0a\xef\x0b\x01\x05\x06\x10\x01\xff\xff\x99\x97\x00\x55\x01\x70')
 482        )
 483
 484    # XXX The following don't test module-level functionality...
 485
 486    def _get_unused_port(self, bind_address='0.0.0.0'):
 487        """Use a temporary socket to elicit an unused ephemeral port.
 488
 489        Args:
 490            bind_address: Hostname or IP address to search for a port on.
 491
 492        Returns: A most likely to be unused port.
 493        """
 494        tempsock = socket.socket()
 495        tempsock.bind((bind_address, 0))
 496        host, port = tempsock.getsockname()
 497        tempsock.close()
 498        return port
 499
 500    def testSockName(self):
 501        # Testing getsockname()
 502        port = self._get_unused_port()
 503        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 504        sock.bind(("0.0.0.0", port))
 505        name = sock.getsockname()
 506        # XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate
 507        # it reasonable to get the host's addr in addition to 0.0.0.0.
 508        # At least for eCos.  This is required for the S/390 to pass.
 509        my_ip_addr = socket.gethostbyname(socket.gethostname())
 510        self.assertIn(name[0], ("0.0.0.0", my_ip_addr), '%s invalid' % name[0])
 511        self.assertEqual(name[1], port)
 512
 513    def testGetSockOpt(self):
 514        # Testing getsockopt()
 515        # We know a socket should start without reuse==0
 516        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 517        reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
 518        self.assertFalse(reuse != 0, "initial mode is reuse")
 519
 520    def testSetSockOpt(self):
 521        # Testing setsockopt()
 522        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 523        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
 524        reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
 525        self.assertFalse(reuse == 0, "failed to set reuse mode")
 526
 527    def testSendAfterClose(self):
 528        # testing send() after close() with timeout
 529        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 530        sock.settimeout(1)
 531        sock.close()
 532        self.assertRaises(socket.error, sock.send, b"spam")
 533
 534    def testNewAttributes(self):
 535        # testing .family, .type and .protocol
 536        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 537        self.assertEqual(sock.family, socket.AF_INET)
 538        self.assertEqual(sock.type, socket.SOCK_STREAM)
 539        self.assertEqual(sock.proto, 0)
 540        sock.close()
 541
 542    def test_getsockaddrarg(self):
 543        host = '0.0.0.0'
 544        port = self._get_unused_port(bind_address=host)
 545        big_port = port + 65536
 546        neg_port = port - 65536
 547        sock = socket.socket()
 548        try:
 549            self.assertRaises(OverflowError, sock.bind, (host, big_port))
 550            self.assertRaises(OverflowError, sock.bind, (host, neg_port))
 551            sock.bind((host, port))
 552        finally:
 553            sock.close()
 554
 555    def test_sock_ioctl(self):
 556        if os.name != "nt":
 557            return
 558        self.assertTrue(hasattr(socket.socket, 'ioctl'))
 559        self.assertTrue(hasattr(socket, 'SIO_RCVALL'))
 560        self.assertTrue(hasattr(socket, 'RCVALL_ON'))
 561        self.assertTrue(hasattr(socket, 'RCVALL_OFF'))
 562        self.assertTrue(hasattr(socket, 'SIO_KEEPALIVE_VALS'))
 563        s = socket.socket()
 564        self.assertRaises(ValueError, s.ioctl, -1, None)
 565        s.ioctl(socket.SIO_KEEPALIVE_VALS, (1, 100, 100))
 566
 567
 568@unittest.skipUnless(thread, 'Threading required for this test.')
 569class BasicTCPTest(SocketConnectedTest):
 570
 571    def __init__(self, methodName='runTest'):
 572        SocketConnectedTest.__init__(self, methodName=methodName)
 573
 574    def testRecv(self):
 575        # Testing large receive over TCP
 576        msg = self.cli_conn.recv(1024)
 577        self.assertEqual(msg, MSG)
 578
 579    def _testRecv(self):
 580        self.serv_conn.send(MSG)
 581
 582    def testOverFlowRecv(self):
 583        # Testing receive in chunks over TCP
 584        seg1 = self.cli_conn.recv(len(MSG) - 3)
 585        seg2 = self.cli_conn.recv(1024)
 586        msg = seg1 + seg2
 587        self.assertEqual(msg, MSG)
 588
 589    def _testOverFlowRecv(self):
 590        self.serv_conn.send(MSG)
 591
 592    def testRecvFrom(self):
 593        # Testing large recvfrom() over TCP
 594        msg, addr = self.cli_conn.recvfrom(1024)
 595        self.assertEqual(msg, MSG)
 596
 597    def _testRecvFrom(self):
 598        self.serv_conn.send(MSG)
 599
 600    def testOverFlowRecvFrom(self):
 601        # Testing recvfrom() in chunks over TCP
 602        seg1, addr = self.cli_conn.recvfrom(len(MSG)-3)
 603        seg2, addr = self.cli_conn.recvfrom(1024)
 604        msg = seg1 + seg2
 605        self.assertEqual(msg, MSG)
 606
 607    def _testOverFlowRecvFrom(self):
 608        self.serv_conn.send(MSG)
 609
 610    def testSendAll(self):
 611        # Testing sendall() with a 2048 byte string over TCP
 612        msg = b''
 613        while 1:
 614            read = self.cli_conn.recv(1024)
 615            if not read:
 616                break
 617            msg += read
 618        self.assertEqual(msg, b'f' * 2048)
 619
 620    def _testSendAll(self):
 621        big_chunk = b'f' * 2048
 622        self.serv_conn.sendall(big_chunk)
 623
 624    def testFromFd(self):
 625        # Testing fromfd()
 626        if not hasattr(socket, "fromfd"):
 627            return # On Windows, this doesn't exist
 628        fd = self.cli_conn.fileno()
 629        sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
 630        msg = sock.recv(1024)
 631        self.assertEqual(msg, MSG)
 632
 633    def _testFromFd(self):
 634        self.serv_conn.send(MSG)
 635
 636    def testDup(self):
 637        # Testing dup()
 638        sock = self.cli_conn.dup()
 639        msg = sock.recv(1024)
 640        self.assertEqual(msg, MSG)
 641
 642    def _testDup(self):
 643        self.serv_conn.send(MSG)
 644
 645    def testShutdown(self):
 646        # Testing shutdown()
 647        msg = self.cli_conn.recv(1024)
 648        self.assertEqual(msg, MSG)
 649        # wait for _testShutdown to finish: on OS X, when the server
 650        # closes the connection the client also becomes disconnected,
 651        # and the client's shutdown call will fail. (Issue #4397.)
 652        self.done.wait()
 653
 654    def _testShutdown(self):
 655        self.serv_conn.send(MSG)
 656        self.serv_conn.shutdown(2)
 657
 658@unittest.skipUnless(thread, 'Threading required for this test.')
 659class BasicUDPTest(ThreadedUDPSocketTest):
 660
 661    def __init__(self, methodName='runTest'):
 662        ThreadedUDPSocketTest.__init__(self, methodName=methodName)
 663
 664    def testSendtoAndRecv(self):
 665        # Testing sendto() and Recv() over UDP
 666        msg = self.serv.recv(len(MSG))
 667        self.assertEqual(msg, MSG)
 668
 669    def _testSendtoAndRecv(self):
 670        self.cli.sendto(MSG, 0, (HOST, self.port))
 671
 672    def testRecvFrom(self):
 673        # Testing recvfrom() over UDP
 674        msg, addr = self.serv.recvfrom(len(MSG))
 675        self.assertEqual(msg, MSG)
 676
 677    def _testRecvFrom(self):
 678        self.cli.sendto(MSG, 0, (HOST, self.port))
 679
 680    def testRecvFromNegative(self):
 681        # Negative lengths passed to recvfrom should give ValueError.
 682        self.assertRaises(ValueError, self.serv.recvfrom, -1)
 683
 684    def _testRecvFromNegative(self):
 685        self.cli.sendto(MSG, 0, (HOST, self.port))
 686
 687@unittest.skipUnless(thread, 'Threading required for this test.')
 688class TCPCloserTest(ThreadedTCPSocketTest):
 689
 690    def testClose(self):
 691        conn, addr = self.serv.accept()
 692        conn.close()
 693
 694        sd = self.cli
 695        read, write, err = select.select([sd], [], [], 1.0)
 696        self.assertEqual(read, [sd])
 697        self.assertEqual(sd.recv(1), b'')
 698
 699        # Calling close() many times should be safe.
 700        conn.close()
 701        conn.close()
 702
 703    def _testClose(self):
 704        self.cli.connect((HOST, self.port))
 705        time.sleep(1.0)
 706
 707@unittest.skipUnless(thread, 'Threading required for this test.')
 708class BasicSocketPairTest(SocketPairTest):
 709
 710    def __init__(self, methodName='runTest'):
 711        SocketPairTest.__init__(self, methodName=methodName)
 712
 713    def testRecv(self):
 714        msg = self.serv.recv(1024)
 715        self.assertEqual(msg, MSG)
 716
 717    def _testRecv(self):
 718        self.cli.send(MSG)
 719
 720    def testSend(self):
 721        self.serv.send(MSG)
 722
 723    def _testSend(self):
 724        msg = self.cli.recv(1024)
 725        self.assertEqual(msg, MSG)
 726
 727@unittest.skipUnless(thread, 'Threading required for this test.')
 728class NonBlockingTCPTests(ThreadedTCPSocketTest):
 729
 730    def __init__(self, methodName='runTest'):
 731        ThreadedTCPSocketTest.__init__(self, methodName=methodName)
 732
 733    def testSetBlocking(self):
 734        # Testing whether set blocking works
 735        self.serv.setblocking(0)
 736        start = time.time()
 737        try:
 738            self.serv.accept()
 739        except socket.error:
 740            pass
 741        end = time.time()
 742        self.assertTrue((end - start) < 1.0, "Error setting non-blocking mode.")
 743
 744    def _testSetBlocking(self):
 745        pass
 746
 747    def testAccept(self):
 748        # Testing non-blocking accept
 749        self.serv.setblocking(0)
 750        try:
 751            conn, addr = self.serv.accept()
 752        except socket.error:
 753            pass
 754        else:
 755            self.fail("Error trying to do non-blocking accept.")
 756        read, write, err = select.select([self.serv], [], [])
 757        if self.serv in read:
 758            conn, addr = self.serv.accept()
 759        else:
 760            self.fail("Error trying to do accept after select.")
 761
 762    def _testAccept(self):
 763        time.sleep(0.1)
 764        self.cli.connect((HOST, self.port))
 765
 766    def testConnect(self):
 767        # Testing non-blocking connect
 768        conn, addr = self.serv.accept()
 769
 770    def _testConnect(self):
 771        self.cli.settimeout(10)
 772        self.cli.connect((HOST, self.port))
 773
 774    def testRecv(self):
 775        # Testing non-blocking recv
 776        conn, addr = self.serv.accept()
 777        conn.setblocking(0)
 778        try:
 779            msg = conn.recv(len(MSG))
 780        except socket.error:
 781            pass
 782        else:
 783            self.fail("Error trying to do non-blocking recv.")
 784        read, write, err = select.select([conn], [], [])
 785        if conn in read:
 786            msg = conn.recv(len(MSG))
 787            self.assertEqual(msg, MSG)
 788        else:
 789            self.fail("Error during select call to non-blocking socket.")
 790
 791    def _testRecv(self):
 792        self.cli.connect((HOST, self.port))
 793        time.sleep(0.1)
 794        self.cli.send(MSG)
 795
 796@unittest.skipUnless(thread, 'Threading required for this test.')
 797class FileObjectClassTestCase(SocketConnectedTest):
 798    """Unit tests for the object returned by socket.makefile()
 799
 800    self.serv_file is the io object returned by makefile() on
 801    the client connection.  You can read from this file to
 802    get output from the server.
 803
 804    self.cli_file is the io object returned by makefile() on the
 805    server connection.  You can write to this file to send output
 806    to the client.
 807    """
 808
 809    bufsize = -1 # Use default buffer size
 810
 811    def __init__(self, methodName='runTest'):
 812        SocketConnectedTest.__init__(self, methodName=methodName)
 813
 814    def setUp(self):
 815        SocketConnectedTest.setUp(self)
 816        self.serv_file = self.cli_conn.makefile('rb', self.bufsize)
 817
 818    def tearDown(self):
 819        self.serv_file.close()
 820        self.assertTrue(self.serv_file.closed)
 821        self.serv_file = None
 822        SocketConnectedTest.tearDown(self)
 823
 824    def clientSetUp(self):
 825        SocketConnectedTest.clientSetUp(self)
 826        self.cli_file = self.serv_conn.makefile('wb')
 827
 828    def clientTearDown(self):
 829        self.cli_file.close()
 830        self.assertTrue(self.cli_file.closed)
 831        self.cli_file = None
 832        SocketConnectedTest.clientTearDown(self)
 833
 834    def testSmallRead(self):
 835        # Performing small file read test
 836        first_seg = self.serv_file.read(len(MSG)-3)
 837        second_seg = self.serv_file.read(3)
 838        msg = first_seg + second_seg
 839        self.assertEqual(msg, MSG)
 840
 841    def _testSmallRead(self):
 842        self.cli_file.write(MSG)
 843        self.cli_file.flush()
 844
 845    def testFullRead(self):
 846        # read until EOF
 847        msg = self.serv_file.read()
 848        self.assertEqual(msg, MSG)
 849
 850    def _testFullRead(self):
 851        self.cli_file.write(MSG)
 852        self.cli_file.close()
 853
 854    def testUnbufferedRead(self):
 855        # Performing unbuffered file read test
 856        buf = b''
 857        while 1:
 858            char = self.serv_file.read(1)
 859            if not char:
 860                break
 861            buf += char
 862        self.assertEqual(buf, MSG)
 863
 864    def _testUnbufferedRead(self):
 865        self.cli_file.write(MSG)
 866        self.cli_file.flush()
 867
 868    def testReadline(self):
 869        # Performing file readline test
 870        line = self.serv_file.readline()
 871        self.assertEqual(line, MSG)
 872
 873    def _testReadline(self):
 874        self.cli_file.write(MSG)
 875        self.cli_file.flush()
 876
 877    def testCloseAfterMakefile(self):
 878        # The file returned by makefile should keep the socket open.
 879        self.cli_conn.close()
 880        # read until EOF
 881        msg = self.serv_file.read()
 882        self.assertEqual(msg, MSG)
 883
 884    def _testCloseAfterMakefile(self):
 885        self.cli_file.write(MSG)
 886        self.cli_file.flush()
 887
 888    def testMakefileAfterMakefileClose(self):
 889        self.serv_file.close()
 890        msg = self.cli_conn.recv(len(MSG))
 891        self.assertEqual(msg, MSG)
 892
 893    def _testMakefileAfterMakefileClose(self):
 894        self.cli_file.write(MSG)
 895        self.cli_file.flush()
 896
 897    def testClosedAttr(self):
 898        self.assertTrue(not self.serv_file.closed)
 899
 900    def _testClosedAttr(self):
 901        self.assertTrue(not self.cli_file.closed)
 902
 903    def testAttributes(self):
 904        self.assertEqual(self.serv_file.mode, 'rb')
 905        self.assertEqual(self.serv_file.name, self.cli_conn.fileno())
 906
 907    def _testAttributes(self):
 908        self.assertEqual(self.cli_file.mode, 'wb')
 909        self.assertEqual(self.cli_file.name, self.serv_conn.fileno())
 910
 911    def testRealClose(self):
 912        self.serv_file.close()
 913        self.assertRaises(ValueError, self.serv_file.fileno)
 914        self.cli_conn.close()
 915        self.assertRaises(socket.error, self.cli_conn.getsockname)
 916
 917    def _testRealClose(self):
 918        pass
 919
 920
 921class FileObjectInterruptedTestCase(unittest.TestCase):
 922    """Test that the file object correctly handles EINTR internally."""
 923
 924    class MockSocket(object):
 925        def __init__(self, recv_funcs=()):
 926            # A generator that returns callables that we'll call for each
 927            # call to recv().
 928            self._recv_step = iter(recv_funcs)
 929
 930        def recv_into(self, buffer):
 931            data = next(self._recv_step)()
 932            assert len(buffer) >= len(data)
 933            buffer[:len(data)] = data
 934            return len(data)
 935
 936        def _decref_socketios(self):
 937            pass
 938
 939        def _textiowrap_for_test(self, buffering=-1):
 940            raw = socket.SocketIO(self, "r")
 941            if buffering < 0:
 942                buffering = io.DEFAULT_BUFFER_SIZE
 943            if buffering == 0:
 944                return raw
 945            buffer = io.BufferedReader(raw, buffering)
 946            text = io.TextIOWrapper(buffer, None, None)
 947            text.mode = "rb"
 948            return text
 949
 950    @staticmethod
 951    def _raise_eintr():
 952        raise socket.error(errno.EINTR)
 953
 954    def _textiowrap_mock_socket(self, mock, buffering=-1):
 955        raw = socket.SocketIO(mock, "r")
 956        if buffering < 0:
 957            buffering = io.DEFAULT_BUFFER_SIZE
 958        if buffering == 0:
 959            return raw
 960        buffer = io.BufferedReader(raw, buffering)
 961        text = io.TextIOWrapper(buffer, None, None)
 962        text.mode = "rb"
 963        return text
 964
 965    def _test_readline(self, size=-1, buffering=-1):
 966        mock_sock = self.MockSocket(recv_funcs=[
 967                lambda : b"This is the first line\nAnd the sec",
 968                self._raise_eintr,
 969                lambda : b"ond line is here\n",
 970                lambda : b"",
 971                lambda : b"",  # XXX(gps): io library does an extra EOF read
 972            ])
 973        fo = mock_sock._textiowrap_for_test(buffering=buffering)
 974        self.assertEquals(fo.readline(size), "This is the first line\n")
 975        self.assertEquals(fo.readline(size), "And the second line is here\n")
 976
 977    def _test_read(self, size=-1, buffering=-1):
 978        mock_sock = self.MockSocket(recv_funcs=[
 979                lambda : b"This is the first line\nAnd the sec",
 980                self._raise_eintr,
 981                lambda : b"ond line is here\n",
 982                lambda : b"",
 983                lambda : b"",  # XXX(gps): io library does an extra EOF read
 984            ])
 985        expecting = (b"This is the first line\n"
 986                     b"And the second line is here\n")
 987        fo = mock_sock._textiowrap_for_test(buffering=buffering)
 988        if buffering == 0:
 989            data = b''
 990        else:
 991            data = ''
 992            expecting = expecting.decode('utf8')
 993        while len(data) != len(expecting):
 994            part = fo.read(size)
 995            if not part:
 996                break
 997            data += part
 998        self.assertEquals(data, expecting)
 999
1000    def test_default(self):
1001        self._test_readline()
1002        self._test_readline(size=100)
1003        self._test_read()
1004        self._test_read(size=100)
1005
1006    def test_with_1k_buffer(self):
1007        self._test_readline(buffering=1024)
1008        self._test_readline(size=100, buffering=1024)
1009        self._test_read(buffering=1024)
1010        self._test_read(size=100, buffering=1024)
1011
1012    def _test_readline_no_buffer(self, size=-1):
1013        mock_sock = self.MockSocket(recv_funcs=[
1014                lambda : b"a",
1015                lambda : b"\n",
1016                lambda : b"B",
1017                self._raise_eintr,
1018                lambda : b"b",
1019                lambda : b"",
1020            ])
1021        fo = mock_sock._textiowrap_for_test(buffering=0)
1022        self.assertEquals(fo.readline(size), b"a\n")
1023        self.assertEquals(fo.readline(size), b"Bb")
1024
1025    def test_no_buffer(self):
1026        self._test_readline_no_buffer()
1027        self._test_readline_no_buffer(size=4)
1028        self._test_read(buffering=0)
1029        self._test_read(size=100, buffering=0)
1030
1031
1032class UnbufferedFileObjectClassTestCase(FileObjectClassTestCase):
1033
1034    """Repeat the tests from FileObjectClassTestCase with bufsize==0.
1035
1036    In this case (and in this case only), it should be possible to
1037    create a file object, read a line from it, create another file
1038    object, read another line from it, without loss of data in the
1039    first file object's buffer.  Note that http.client relies on this
1040    when reading multiple requests from the same socket."""
1041
1042    bufsize = 0 # Use unbuffered mode
1043
1044    def testUnbufferedReadline(self):
1045        # Read a line, create a new file object, read another line with it
1046        line = self.serv_file.readline() # first line
1047        self.assertEqual(line, b"A. " + MSG) # first line
1048        self.serv_file = self.cli_conn.makefile('rb', 0)
1049        line = self.serv_file.readline() # second line
1050        self.assertEqual(line, b"B. " + MSG) # second line
1051
1052    def _testUnbufferedReadline(self):
1053        self.cli_file.write(b"A. " + MSG)
1054        self.cli_file.write(b"B. " + MSG)
1055        self.cli_file.flush()
1056
1057    def testMakefileClose(self):
1058        # The file returned by makefile should keep the socket open...
1059        self.cli_conn.close()
1060        msg = self.cli_conn.recv(1024)
1061        self.assertEqual(msg, MSG)
1062        # ...until the file is itself closed
1063        self.serv_file.close()
1064        self.assertRaises(socket.error, self.cli_conn.recv, 1024)
1065
1066    def _testMakefileClose(self):
1067        self.cli_file.write(MSG)
1068        self.cli_file.flush()
1069
1070    def testMakefileCloseSocketDestroy(self):
1071        refcount_before = sys.getrefcount(self.cli_conn)
1072        self.serv_file.close()
1073        refcount_after = sys.getrefcount(self.cli_conn)
1074        self.assertEqual(refcount_before - 1, refcount_after)
1075
1076    def _testMakefileCloseSocketDestroy(self):
1077        pass
1078
1079
1080class LineBufferedFileObjectClassTestCase(FileObjectClassTestCase):
1081
1082    bufsize = 1 # Default-buffered for reading; line-buffered for writing
1083
1084
1085class SmallBufferedFileObjectClassTestCase(FileObjectClassTestCase):
1086
1087    bufsize = 2 # Exercise the buffering code
1088
1089
1090class NetworkConnectionTest(object):
1091    """Prove network connection."""
1092
1093    def clientSetUp(self):
1094        # We're inherited below by BasicTCPTest2, which also inherits
1095        # BasicTCPTest, which defines self.port referenced below.
1096        self.cli = socket.create_connection((HOST, self.port))
1097        self.serv_conn = self.cli
1098
1099class BasicTCPTest2(NetworkConnectionTest, BasicTCPTest):
1100    """Tests that NetworkConnection does not break existing TCP functionality.
1101    """
1102
1103class NetworkConnectionNoServer(unittest.TestCase):
1104
1105    def testWithoutServer(self):
1106        port = support.find_unused_port()
1107        self.assertRaises(
1108            socket.error,
1109            lambda: socket.create_connection((HOST, port))
1110        )
1111
1112@unittest.skipUnless(thread, 'Threading required for this test.')
1113class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest):
1114
1115    def __init__(self, methodName='runTest'):
1116        SocketTCPTest.__init__(self, methodName=methodName)
1117        ThreadableTest.__init__(self)
1118
1119    def clientSetUp(self):
1120        self.source_port = support.find_unused_port()
1121
1122    def clientTearDown(self):
1123        self.cli.close()
1124        self.cli = None
1125        ThreadableTest.clientTearDown(self)
1126
1127    def _justAccept(self):
1128        conn, addr = self.serv.accept()
1129
1130    testFamily = _justAccept
1131    def _testFamily(self):
1132        self.cli = socket.create_connection((HOST, self.port), timeout=30)
1133        self.assertEqual(self.cli.family, 2)
1134
1135    testSourceAddress = _justAccept
1136    def _testSourceAddress(self):
1137        self.cli = socket.create_connection((HOST, self.port), timeout=30,
1138                source_address=('', self.source_port))
1139        self.assertEqual(self.cli.getsockname()[1], self.source_port)
1140        # The port number being used is sufficient to show that the bind()
1141        # call happened.
1142
1143    testTimeoutDefault = _justAccept
1144    def _testTimeoutDefault(self):
1145        # passing no explicit timeout uses socket's global default
1146        self.assertTrue(socket.getdefaulttimeout() is None)
1147        socket.setdefaulttimeout(42)
1148        try:
1149            self.cli = socket.create_connection((HOST, self.port))
1150        finally:
1151            socket.setdefaulttimeout(None)
1152        self.assertEquals(self.cli.gettimeout(), 42)
1153
1154    testTimeoutNone = _justAccept
1155    def _testTimeoutNone(self):
1156        # None timeout means the same as sock.settimeout(None)
1157        self.assertTrue(socket.getdefaulttimeout() is None)
1158        socket.setdefaulttimeout(30)
1159        try:
1160            self.cli = socket.create_connection((HOST, self.port), timeout=None)
1161        finally:
1162            socket.setdefaulttimeout(None)
1163        self.assertEqual(self.cli.gettimeout(), None)
1164
1165    testTimeoutValueNamed = _justAccept
1166    def _testTimeoutValueNamed(self):
1167        self.cli = socket.create_connection((HOST, self.port), timeout=30)
1168        self.assertEqual(self.cli.gettimeout(), 30)
1169
1170    testTimeoutValueNonamed = _justAccept
1171    def _testTimeoutValueNonamed(self):
1172        self.cli = socket.create_connection((HOST, self.port), 30)
1173        self.assertEqual(self.cli.gettimeout(), 30)
1174
1175@unittest.skipUnless(thread, 'Threading required for this test.')
1176class NetworkConnectionBehaviourTest(SocketTCPTest, ThreadableTest):
1177
1178    def __init__(self, methodName='runTest'):
1179        SocketTCPTest.__init__(self, methodName=methodName)
1180        ThreadableTest.__init__(self)
1181
1182    def clientSetUp(self):
1183        pass
1184
1185    def clientTearDown(self):
1186        self.cli.close()
1187        self.cli = None
1188        ThreadableTest.clientTearDown(self)
1189
1190    def testInsideTimeout(self):
1191        conn, addr = self.serv.accept()
1192        time.sleep(3)
1193        conn.send(b"done!")
1194    testOutsideTimeout = testInsideTimeout
1195
1196    def _testInsideTimeout(self):
1197        self.cli = sock = socket.create_connection((HOST, self.port))
1198        data = sock.recv(5)
1199        self.assertEqual(data, b"done!")
1200
1201    def _testOutsideTimeout(self):
1202        self.cli = sock = socket.create_connection((HOST, self.port), timeout=1)
1203        self.assertRaises(socket.timeout, lambda: sock.recv(5))
1204
1205
1206class TCPTimeoutTest(SocketTCPTest):
1207
1208    def testTCPTimeout(self):
1209        def raise_timeout(*args, **kwargs):
1210            self.serv.settimeout(1.0)
1211            self.serv.accept()
1212        self.assertRaises(socket.timeout, raise_timeout,
1213                              "Error generating a timeout exception (TCP)")
1214
1215    def testTimeoutZero(self):
1216        ok = False
1217        try:
1218            self.serv.settimeout(0.0)
1219            foo = self.serv.accept()
1220        except socket.timeout:
1221            self.fail("caught timeout instead of error (TCP)")
1222        except socket.error:
1223            ok = True
1224        except:
1225            self.fail("caught unexpected exception (TCP)")
1226        if not ok:
1227            self.fail("accept() returned success when we did not expect it")
1228
1229    def testInterruptedTimeout(self):
1230        # XXX I don't know how to do this test on MSWindows or any other
1231        # plaform that doesn't support signal.alarm() or os.kill(), though
1232        # the bug should have existed on all platforms.
1233        if not hasattr(signal, "alarm"):
1234            return                  # can only test on *nix
1235        self.serv.settimeout(5.0)   # must be longer than alarm
1236        class Alarm(Exception):
1237            pass
1238        def alarm_handler(signal, frame):
1239            raise Alarm
1240        old_alarm = signal.signal(signal.SIGALRM, alarm_handler)
1241        try:
1242            signal.alarm(2)    # POSIX allows alarm to be up to 1 second early
1243            try:
1244                foo = self.serv.accept()
1245            except socket.timeout:
1246                self.fail("caught timeout instead of Alarm")
1247            except Alarm:
1248                pass
1249            except:
1250                self.fail("caught other exception instead of Alarm:"
1251                          " %s(%s):\n%s" %
1252                          (sys.exc_info()[:2] + (traceback.format_exc(),)))
1253            else:
1254                self.fail("nothing caught")
1255            finally:
1256                signal.alarm(0)         # shut off alarm
1257        except Alarm:
1258            self.fail("got Alarm in wrong place")
1259        finally:
1260            # no alarm can be pending.  Safe to restore old handler.
1261            signal.signal(signal.SIGALRM, old_alarm)
1262
1263class UDPTimeoutTest(SocketTCPTest):
1264
1265    def testUDPTimeout(self):
1266        def raise_timeout(*args, **kwargs):
1267            self.serv.settimeout(1.0)
1268            self.serv.recv(1024)
1269        self.assertRaises(socket.timeout, raise_timeout,
1270                              "Error generating a timeout exception (UDP)")
1271
1272    def testTimeoutZero(self):
1273        ok = False
1274        try:
1275            self.serv.settimeout(0.0)
1276            foo = self.serv.recv(1024)
1277        except socket.timeout:
1278            self.fail("caught timeout instead of error (UDP)")
1279        except socket.error:
1280            ok = True
1281        except:
1282            self.fail("caught unexpected exception (UDP)")
1283        if not ok:
1284            self.fail("recv() returned success when we did not expect it")
1285
1286class TestExceptions(unittest.TestCase):
1287
1288    def testExceptionTree(self):
1289        self.assertTrue(issubclass(socket.error, Exception))
1290        self.assertTrue(issubclass(socket.herror, socket.error))
1291        self.assertTrue(issubclass(socket.gaierror, socket.error))
1292        self.assertTrue(issubclass(socket.timeout, socket.error))
1293
1294class TestLinuxAbstractNamespace(unittest.TestCase):
1295
1296    UNIX_PATH_MAX = 108
1297
1298    def testLinuxAbstractNamespace(self):
1299        address = b"\x00python-test-hello\x00\xff"
1300        s1 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1301        s1.bind(address)
1302        s1.listen(1)
1303        s2 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1304        s2.connect(s1.getsockname())
1305        s1.accept()
1306        self.assertEqual(s1.getsockname(), address)
1307        self.assertEqual(s2.getpeername(), address)
1308
1309    def testMaxName(self):
1310        address = b"\x00" + b"h" * (self.UNIX_PATH_MAX - 1)
1311        s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1312        s.bind(address)
1313        self.assertEqual(s.getsockname(), address)
1314
1315    def testNameOverflow(self):
1316        address = "\x00" + "h" * self.UNIX_PATH_MAX
1317        s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1318        self.assertRaises(socket.error, s.bind, address)
1319
1320
1321@unittest.skipUnless(thread, 'Threading required for this test.')
1322class BufferIOTest(SocketConnectedTest):
1323    """
1324    Test the buffer versions of socket.recv() and socket.send().
1325    """
1326    def __init__(self, methodName='runTest'):
1327        SocketConnectedTest.__init__(self, methodName=methodName)
1328
1329    def testRecvIntoArray(self):
1330        buf = bytearray(1024)
1331        nbytes = self.cli_conn.recv_into(buf)
1332        self.assertEqual(nbytes, len(MSG))
1333        msg = buf[:len(MSG)]
1334        self.assertEqual(msg, MSG)
1335
1336    def _testRecvIntoArray(self):
1337        buf = bytes(MSG)
1338        self.serv_conn.send(buf)
1339
1340    def testRecvIntoBytearray(self):
1341        buf = bytearray(1024)
1342        nbytes = self.cli_conn.recv_into(buf)
1343        self.assertEqual(nbytes, len(MSG))
1344        msg = buf[:len(MSG)]
1345        self.assertEqual(msg, MSG)
1346
1347    _testRecvIntoBytearray = _testRecvIntoArray
1348
1349    def testRecvIntoMemoryview(self):
1350        buf = bytearray(1024)
1351        nbytes = self.cli_conn.recv_into(memoryview(buf))
1352        self.assertEqual(nbytes, len(MSG))
1353        msg = buf[:len(MSG)]
1354        self.assertEqual(msg, MSG)
1355
1356    _testRecvIntoMemoryview = _testRecvIntoArray
1357
1358    def testRecvFromIntoArray(self):
1359        buf = bytearray(1024)
1360        nbytes, addr = self.cli_conn.recvfrom_into(buf)
1361        self.assertEqual(nbytes, len(MSG))
1362        msg = buf[:len(MSG)]
1363        self.assertEqual(msg, MSG)
1364
1365    def _testRecvFromIntoArray(self):
1366        buf = bytes(MSG)
1367        self.serv_conn.send(buf)
1368
1369    def testRecvFromIntoBytearray(self):
1370        buf = bytearray(1024)
1371        nbytes, addr = self.cli_conn.recvfrom_into(buf)
1372        self.assertEqual(nbytes, len(MSG))
1373        msg = buf[:len(MSG)]
1374        self.assertEqual(msg, MSG)
1375
1376    _testRecvFromIntoBytearray = _testRecvFromIntoArray
1377
1378    def testRecvFromIntoMemoryview(self):
1379        buf = bytearray(1024)
1380        nbytes, addr = self.cli_conn.recvfrom_into(memoryview(buf))
1381        self.assertEqual(nbytes, len(MSG))
1382        msg = buf[:len(MSG)]
1383        self.assertEqual(msg, MSG)
1384
1385    _testRecvFromIntoMemoryview = _testRecvFromIntoArray
1386
1387
1388TIPC_STYPE = 2000
1389TIPC_LOWER = 200
1390TIPC_UPPER = 210
1391
1392def isTipcAvailable():
1393    """Check if the TIPC module is loaded
1394
1395    The TIPC module is not loaded automatically on Ubuntu and probably
1396    other Linux distros.
1397    """
1398    if not hasattr(socket, "AF_TIPC"):
1399        return False
1400    if not os.path.isfile("/proc/modules"):
1401        return False
1402    with open("/proc/modules") as f:
1403        for line in f:
1404            if line.startswith("tipc "):
1405                return True
1406    if support.verbose:
1407        print("TIPC module is not loaded, please 'sudo modprobe tipc'")
1408    return False
1409
1410class TIPCTest (unittest.TestCase):
1411    def testRDM(self):
1412        srv = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
1413        cli = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
1414
1415        srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1416        srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
1417                TIPC_LOWER, TIPC_UPPER)
1418        srv.bind(srvaddr)
1419
1420        sendaddr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
1421                TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
1422        cli.sendto(MSG, sendaddr)
1423
1424        msg, recvaddr = srv.recvfrom(1024)
1425
1426        self.assertEqual(cli.getsockname(), recvaddr)
1427        self.assertEqual(msg, MSG)
1428
1429
1430class TIPCThreadableTest (unittest.TestCase, ThreadableTest):
1431    def __init__(self, methodName = 'runTest'):
1432        unittest.TestCase.__init__(self, methodName = methodName)
1433        ThreadableTest.__init__(self)
1434
1435    def setUp(self):
1436        self.srv = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
1437        self.srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1438        srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
1439                TIPC_LOWER, TIPC_UPPER)
1440        self.srv.bind(srvaddr)
1441        self.srv.listen(5)
1442        self.serverExplicitReady()
1443        self.conn, self.connaddr = self.srv.accept()
1444
1445    def clientSetUp(self):
1446        # The is a hittable race between serverExplicitReady() and the
1447        # accept() call; sleep a little while to avoid it, otherwise
1448        # we could get an exception
1449        time.sleep(0.1)
1450        self.cli = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
1451        addr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
1452                TIPC_LOWER + int((TIPC_UPPER - TIPC_LOWER) / 2), 0)
1453        self.cli.connect(addr)
1454        self.cliaddr = self.cli.getsockname()
1455
1456    def testStream(self):
1457        msg = self.conn.recv(1024)
1458        self.assertEqual(msg, MSG)
1459        self.assertEqual(self.cliaddr, self.connaddr)
1460
1461    def _testStream(self):
1462        self.cli.send(MSG)
1463        self.cli.close()
1464
1465
1466def test_main():
1467    tests = [GeneralModuleTests, BasicTCPTest, TCPCloserTest, TCPTimeoutTest,
1468             TestExceptions, BufferIOTest, BasicTCPTest2, BasicUDPTest, UDPTimeoutTest ]
1469
1470    tests.extend([
1471        NonBlockingTCPTests,
1472        FileObjectClassTestCase,
1473        FileObjectInterruptedTestCase,
1474        UnbufferedFileObjectClassTestCase,
1475        LineBuffere

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