PageRenderTime 9ms CodeModel.GetById 2ms app.highlight 105ms RepoModel.GetById 1ms app.codeStats 0ms

/lib-python/2.7/test/test_socket.py

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