PageRenderTime 281ms CodeModel.GetById 69ms app.highlight 71ms RepoModel.GetById 107ms app.codeStats 1ms

/dj14_py27/win/Lib/test/test_socket.py

https://bitbucket.org/kenial/portable-django
Python | 1627 lines | 1433 code | 97 blank | 97 comment | 55 complexity | 4e1f9a6db1ad9d08eb8f68c631892806 MD5 | raw file

Large files files are truncated, but you can click here to view the full 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        try:
 255            p.fileno()
 256        except ReferenceError:
 257            pass
 258        else:
 259            self.fail('Socket proxy still exists')
 260
 261    def testSocketError(self):
 262        # Testing socket module exceptions
 263        def raise_error(*args, **kwargs):
 264            raise socket.error
 265        def raise_herror(*args, **kwargs):
 266            raise socket.herror
 267        def raise_gaierror(*args, **kwargs):
 268            raise socket.gaierror
 269        self.assertRaises(socket.error, raise_error,
 270                              "Error raising socket exception.")
 271        self.assertRaises(socket.error, raise_herror,
 272                              "Error raising socket exception.")
 273        self.assertRaises(socket.error, raise_gaierror,
 274                              "Error raising socket exception.")
 275
 276    def testSendtoErrors(self):
 277        # Testing that sendto doens't masks failures. See #10169.
 278        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
 279        self.addCleanup(s.close)
 280        s.bind(('', 0))
 281        sockname = s.getsockname()
 282        # 2 args
 283        with self.assertRaises(UnicodeEncodeError):
 284            s.sendto(u'\u2620', sockname)
 285        with self.assertRaises(TypeError) as cm:
 286            s.sendto(5j, sockname)
 287        self.assertIn('not complex', str(cm.exception))
 288        with self.assertRaises(TypeError) as cm:
 289            s.sendto('foo', None)
 290        self.assertIn('not NoneType', str(cm.exception))
 291        # 3 args
 292        with self.assertRaises(UnicodeEncodeError):
 293            s.sendto(u'\u2620', 0, sockname)
 294        with self.assertRaises(TypeError) as cm:
 295            s.sendto(5j, 0, sockname)
 296        self.assertIn('not complex', str(cm.exception))
 297        with self.assertRaises(TypeError) as cm:
 298            s.sendto('foo', 0, None)
 299        self.assertIn('not NoneType', str(cm.exception))
 300        with self.assertRaises(TypeError) as cm:
 301            s.sendto('foo', 'bar', sockname)
 302        self.assertIn('an integer is required', str(cm.exception))
 303        with self.assertRaises(TypeError) as cm:
 304            s.sendto('foo', None, None)
 305        self.assertIn('an integer is required', str(cm.exception))
 306        # wrong number of args
 307        with self.assertRaises(TypeError) as cm:
 308            s.sendto('foo')
 309        self.assertIn('(1 given)', str(cm.exception))
 310        with self.assertRaises(TypeError) as cm:
 311            s.sendto('foo', 0, sockname, 4)
 312        self.assertIn('(4 given)', str(cm.exception))
 313
 314
 315    def testCrucialConstants(self):
 316        # Testing for mission critical constants
 317        socket.AF_INET
 318        socket.SOCK_STREAM
 319        socket.SOCK_DGRAM
 320        socket.SOCK_RAW
 321        socket.SOCK_RDM
 322        socket.SOCK_SEQPACKET
 323        socket.SOL_SOCKET
 324        socket.SO_REUSEADDR
 325
 326    def testHostnameRes(self):
 327        # Testing hostname resolution mechanisms
 328        hostname = socket.gethostname()
 329        try:
 330            ip = socket.gethostbyname(hostname)
 331        except socket.error:
 332            # Probably name lookup wasn't set up right; skip this test
 333            return
 334        self.assertTrue(ip.find('.') >= 0, "Error resolving host to ip.")
 335        try:
 336            hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
 337        except socket.error:
 338            # Probably a similar problem as above; skip this test
 339            return
 340        all_host_names = [hostname, hname] + aliases
 341        fqhn = socket.getfqdn(ip)
 342        if not fqhn in all_host_names:
 343            self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names)))
 344
 345    def testRefCountGetNameInfo(self):
 346        # Testing reference count for getnameinfo
 347        if hasattr(sys, "getrefcount"):
 348            try:
 349                # On some versions, this loses a reference
 350                orig = sys.getrefcount(__name__)
 351                socket.getnameinfo(__name__,0)
 352            except TypeError:
 353                self.assertEqual(sys.getrefcount(__name__), orig,
 354                                 "socket.getnameinfo loses a reference")
 355
 356    def testInterpreterCrash(self):
 357        # Making sure getnameinfo doesn't crash the interpreter
 358        try:
 359            # On some versions, this crashes the interpreter.
 360            socket.getnameinfo(('x', 0, 0, 0), 0)
 361        except socket.error:
 362            pass
 363
 364    def testNtoH(self):
 365        # This just checks that htons etc. are their own inverse,
 366        # when looking at the lower 16 or 32 bits.
 367        sizes = {socket.htonl: 32, socket.ntohl: 32,
 368                 socket.htons: 16, socket.ntohs: 16}
 369        for func, size in sizes.items():
 370            mask = (1L<<size) - 1
 371            for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210):
 372                self.assertEqual(i & mask, func(func(i&mask)) & mask)
 373
 374            swapped = func(mask)
 375            self.assertEqual(swapped & mask, mask)
 376            self.assertRaises(OverflowError, func, 1L<<34)
 377
 378    def testNtoHErrors(self):
 379        good_values = [ 1, 2, 3, 1L, 2L, 3L ]
 380        bad_values = [ -1, -2, -3, -1L, -2L, -3L ]
 381        for k in good_values:
 382            socket.ntohl(k)
 383            socket.ntohs(k)
 384            socket.htonl(k)
 385            socket.htons(k)
 386        for k in bad_values:
 387            self.assertRaises(OverflowError, socket.ntohl, k)
 388            self.assertRaises(OverflowError, socket.ntohs, k)
 389            self.assertRaises(OverflowError, socket.htonl, k)
 390            self.assertRaises(OverflowError, socket.htons, k)
 391
 392    def testGetServBy(self):
 393        eq = self.assertEqual
 394        # Find one service that exists, then check all the related interfaces.
 395        # I've ordered this by protocols that have both a tcp and udp
 396        # protocol, at least for modern Linuxes.
 397        if (sys.platform.startswith('linux') or
 398            sys.platform.startswith('freebsd') or
 399            sys.platform.startswith('netbsd') or
 400            sys.platform == 'darwin'):
 401            # avoid the 'echo' service on this platform, as there is an
 402            # assumption breaking non-standard port/protocol entry
 403            services = ('daytime', 'qotd', 'domain')
 404        else:
 405            services = ('echo', 'daytime', 'domain')
 406        for service in services:
 407            try:
 408                port = socket.getservbyname(service, 'tcp')
 409                break
 410            except socket.error:
 411                pass
 412        else:
 413            raise socket.error
 414        # Try same call with optional protocol omitted
 415        port2 = socket.getservbyname(service)
 416        eq(port, port2)
 417        # Try udp, but don't barf it it doesn't exist
 418        try:
 419            udpport = socket.getservbyname(service, 'udp')
 420        except socket.error:
 421            udpport = None
 422        else:
 423            eq(udpport, port)
 424        # Now make sure the lookup by port returns the same service name
 425        eq(socket.getservbyport(port2), service)
 426        eq(socket.getservbyport(port, 'tcp'), service)
 427        if udpport is not None:
 428            eq(socket.getservbyport(udpport, 'udp'), service)
 429        # Make sure getservbyport does not accept out of range ports.
 430        self.assertRaises(OverflowError, socket.getservbyport, -1)
 431        self.assertRaises(OverflowError, socket.getservbyport, 65536)
 432
 433    def testDefaultTimeout(self):
 434        # Testing default timeout
 435        # The default timeout should initially be None
 436        self.assertEqual(socket.getdefaulttimeout(), None)
 437        s = socket.socket()
 438        self.assertEqual(s.gettimeout(), None)
 439        s.close()
 440
 441        # Set the default timeout to 10, and see if it propagates
 442        socket.setdefaulttimeout(10)
 443        self.assertEqual(socket.getdefaulttimeout(), 10)
 444        s = socket.socket()
 445        self.assertEqual(s.gettimeout(), 10)
 446        s.close()
 447
 448        # Reset the default timeout to None, and see if it propagates
 449        socket.setdefaulttimeout(None)
 450        self.assertEqual(socket.getdefaulttimeout(), None)
 451        s = socket.socket()
 452        self.assertEqual(s.gettimeout(), None)
 453        s.close()
 454
 455        # Check that setting it to an invalid value raises ValueError
 456        self.assertRaises(ValueError, socket.setdefaulttimeout, -1)
 457
 458        # Check that setting it to an invalid type raises TypeError
 459        self.assertRaises(TypeError, socket.setdefaulttimeout, "spam")
 460
 461    def testIPv4_inet_aton_fourbytes(self):
 462        if not hasattr(socket, 'inet_aton'):
 463            return  # No inet_aton, nothing to check
 464        # Test that issue1008086 and issue767150 are fixed.
 465        # It must return 4 bytes.
 466        self.assertEqual('\x00'*4, socket.inet_aton('0.0.0.0'))
 467        self.assertEqual('\xff'*4, socket.inet_aton('255.255.255.255'))
 468
 469    def testIPv4toString(self):
 470        if not hasattr(socket, 'inet_pton'):
 471            return # No inet_pton() on this platform
 472        from socket import inet_aton as f, inet_pton, AF_INET
 473        g = lambda a: inet_pton(AF_INET, a)
 474
 475        self.assertEqual('\x00\x00\x00\x00', f('0.0.0.0'))
 476        self.assertEqual('\xff\x00\xff\x00', f('255.0.255.0'))
 477        self.assertEqual('\xaa\xaa\xaa\xaa', f('170.170.170.170'))
 478        self.assertEqual('\x01\x02\x03\x04', f('1.2.3.4'))
 479        self.assertEqual('\xff\xff\xff\xff', f('255.255.255.255'))
 480
 481        self.assertEqual('\x00\x00\x00\x00', g('0.0.0.0'))
 482        self.assertEqual('\xff\x00\xff\x00', g('255.0.255.0'))
 483        self.assertEqual('\xaa\xaa\xaa\xaa', g('170.170.170.170'))
 484        self.assertEqual('\xff\xff\xff\xff', g('255.255.255.255'))
 485
 486    def testIPv6toString(self):
 487        if not hasattr(socket, 'inet_pton'):
 488            return # No inet_pton() on this platform
 489        try:
 490            from socket import inet_pton, AF_INET6, has_ipv6
 491            if not has_ipv6:
 492                return
 493        except ImportError:
 494            return
 495        f = lambda a: inet_pton(AF_INET6, a)
 496
 497        self.assertEqual('\x00' * 16, f('::'))
 498        self.assertEqual('\x00' * 16, f('0::0'))
 499        self.assertEqual('\x00\x01' + '\x00' * 14, f('1::'))
 500        self.assertEqual(
 501            '\x45\xef\x76\xcb\x00\x1a\x56\xef\xaf\xeb\x0b\xac\x19\x24\xae\xae',
 502            f('45ef:76cb:1a:56ef:afeb:bac:1924:aeae')
 503        )
 504
 505    def testStringToIPv4(self):
 506        if not hasattr(socket, 'inet_ntop'):
 507            return # No inet_ntop() on this platform
 508        from socket import inet_ntoa as f, inet_ntop, AF_INET
 509        g = lambda a: inet_ntop(AF_INET, a)
 510
 511        self.assertEqual('1.0.1.0', f('\x01\x00\x01\x00'))
 512        self.assertEqual('170.85.170.85', f('\xaa\x55\xaa\x55'))
 513        self.assertEqual('255.255.255.255', f('\xff\xff\xff\xff'))
 514        self.assertEqual('1.2.3.4', f('\x01\x02\x03\x04'))
 515
 516        self.assertEqual('1.0.1.0', g('\x01\x00\x01\x00'))
 517        self.assertEqual('170.85.170.85', g('\xaa\x55\xaa\x55'))
 518        self.assertEqual('255.255.255.255', g('\xff\xff\xff\xff'))
 519
 520    def testStringToIPv6(self):
 521        if not hasattr(socket, 'inet_ntop'):
 522            return # No inet_ntop() on this platform
 523        try:
 524            from socket import inet_ntop, AF_INET6, has_ipv6
 525            if not has_ipv6:
 526                return
 527        except ImportError:
 528            return
 529        f = lambda a: inet_ntop(AF_INET6, a)
 530
 531        self.assertEqual('::', f('\x00' * 16))
 532        self.assertEqual('::1', f('\x00' * 15 + '\x01'))
 533        self.assertEqual(
 534            'aef:b01:506:1001:ffff:9997:55:170',
 535            f('\x0a\xef\x0b\x01\x05\x06\x10\x01\xff\xff\x99\x97\x00\x55\x01\x70')
 536        )
 537
 538    # XXX The following don't test module-level functionality...
 539
 540    def _get_unused_port(self, bind_address='0.0.0.0'):
 541        """Use a temporary socket to elicit an unused ephemeral port.
 542
 543        Args:
 544            bind_address: Hostname or IP address to search for a port on.
 545
 546        Returns: A most likely to be unused port.
 547        """
 548        tempsock = socket.socket()
 549        tempsock.bind((bind_address, 0))
 550        host, port = tempsock.getsockname()
 551        tempsock.close()
 552        return port
 553
 554    def testSockName(self):
 555        # Testing getsockname()
 556        port = self._get_unused_port()
 557        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 558        self.addCleanup(sock.close)
 559        sock.bind(("0.0.0.0", port))
 560        name = sock.getsockname()
 561        # XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate
 562        # it reasonable to get the host's addr in addition to 0.0.0.0.
 563        # At least for eCos.  This is required for the S/390 to pass.
 564        try:
 565            my_ip_addr = socket.gethostbyname(socket.gethostname())
 566        except socket.error:
 567            # Probably name lookup wasn't set up right; skip this test
 568            return
 569        self.assertIn(name[0], ("0.0.0.0", my_ip_addr), '%s invalid' % name[0])
 570        self.assertEqual(name[1], port)
 571
 572    def testGetSockOpt(self):
 573        # Testing getsockopt()
 574        # We know a socket should start without reuse==0
 575        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 576        self.addCleanup(sock.close)
 577        reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
 578        self.assertFalse(reuse != 0, "initial mode is reuse")
 579
 580    def testSetSockOpt(self):
 581        # Testing setsockopt()
 582        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 583        self.addCleanup(sock.close)
 584        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
 585        reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
 586        self.assertFalse(reuse == 0, "failed to set reuse mode")
 587
 588    def testSendAfterClose(self):
 589        # testing send() after close() with timeout
 590        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 591        sock.settimeout(1)
 592        sock.close()
 593        self.assertRaises(socket.error, sock.send, "spam")
 594
 595    def testNewAttributes(self):
 596        # testing .family, .type and .protocol
 597        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 598        self.assertEqual(sock.family, socket.AF_INET)
 599        self.assertEqual(sock.type, socket.SOCK_STREAM)
 600        self.assertEqual(sock.proto, 0)
 601        sock.close()
 602
 603    def test_getsockaddrarg(self):
 604        host = '0.0.0.0'
 605        port = self._get_unused_port(bind_address=host)
 606        big_port = port + 65536
 607        neg_port = port - 65536
 608        sock = socket.socket()
 609        try:
 610            self.assertRaises(OverflowError, sock.bind, (host, big_port))
 611            self.assertRaises(OverflowError, sock.bind, (host, neg_port))
 612            sock.bind((host, port))
 613        finally:
 614            sock.close()
 615
 616    @unittest.skipUnless(os.name == "nt", "Windows specific")
 617    def test_sock_ioctl(self):
 618        self.assertTrue(hasattr(socket.socket, 'ioctl'))
 619        self.assertTrue(hasattr(socket, 'SIO_RCVALL'))
 620        self.assertTrue(hasattr(socket, 'RCVALL_ON'))
 621        self.assertTrue(hasattr(socket, 'RCVALL_OFF'))
 622        self.assertTrue(hasattr(socket, 'SIO_KEEPALIVE_VALS'))
 623        s = socket.socket()
 624        self.addCleanup(s.close)
 625        self.assertRaises(ValueError, s.ioctl, -1, None)
 626        s.ioctl(socket.SIO_KEEPALIVE_VALS, (1, 100, 100))
 627
 628    def testGetaddrinfo(self):
 629        try:
 630            socket.getaddrinfo('localhost', 80)
 631        except socket.gaierror as err:
 632            if err.errno == socket.EAI_SERVICE:
 633                # see http://bugs.python.org/issue1282647
 634                self.skipTest("buggy libc version")
 635            raise
 636        # len of every sequence is supposed to be == 5
 637        for info in socket.getaddrinfo(HOST, None):
 638            self.assertEqual(len(info), 5)
 639        # host can be a domain name, a string representation of an
 640        # IPv4/v6 address or None
 641        socket.getaddrinfo('localhost', 80)
 642        socket.getaddrinfo('127.0.0.1', 80)
 643        socket.getaddrinfo(None, 80)
 644        if SUPPORTS_IPV6:
 645            socket.getaddrinfo('::1', 80)
 646        # port can be a string service name such as "http", a numeric
 647        # port number or None
 648        socket.getaddrinfo(HOST, "http")
 649        socket.getaddrinfo(HOST, 80)
 650        socket.getaddrinfo(HOST, None)
 651        # test family and socktype filters
 652        infos = socket.getaddrinfo(HOST, None, socket.AF_INET)
 653        for family, _, _, _, _ in infos:
 654            self.assertEqual(family, socket.AF_INET)
 655        infos = socket.getaddrinfo(HOST, None, 0, socket.SOCK_STREAM)
 656        for _, socktype, _, _, _ in infos:
 657            self.assertEqual(socktype, socket.SOCK_STREAM)
 658        # test proto and flags arguments
 659        socket.getaddrinfo(HOST, None, 0, 0, socket.SOL_TCP)
 660        socket.getaddrinfo(HOST, None, 0, 0, 0, socket.AI_PASSIVE)
 661        # a server willing to support both IPv4 and IPv6 will
 662        # usually do this
 663        socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
 664                           socket.AI_PASSIVE)
 665
 666
 667    def check_sendall_interrupted(self, with_timeout):
 668        # socketpair() is not stricly required, but it makes things easier.
 669        if not hasattr(signal, 'alarm') or not hasattr(socket, 'socketpair'):
 670            self.skipTest("signal.alarm and socket.socketpair required for this test")
 671        # Our signal handlers clobber the C errno by calling a math function
 672        # with an invalid domain value.
 673        def ok_handler(*args):
 674            self.assertRaises(ValueError, math.acosh, 0)
 675        def raising_handler(*args):
 676            self.assertRaises(ValueError, math.acosh, 0)
 677            1 // 0
 678        c, s = socket.socketpair()
 679        old_alarm = signal.signal(signal.SIGALRM, raising_handler)
 680        try:
 681            if with_timeout:
 682                # Just above the one second minimum for signal.alarm
 683                c.settimeout(1.5)
 684            with self.assertRaises(ZeroDivisionError):
 685                signal.alarm(1)
 686                c.sendall(b"x" * (1024**2))
 687            if with_timeout:
 688                signal.signal(signal.SIGALRM, ok_handler)
 689                signal.alarm(1)
 690                self.assertRaises(socket.timeout, c.sendall, b"x" * (1024**2))
 691        finally:
 692            signal.signal(signal.SIGALRM, old_alarm)
 693            c.close()
 694            s.close()
 695
 696    def test_sendall_interrupted(self):
 697        self.check_sendall_interrupted(False)
 698
 699    def test_sendall_interrupted_with_timeout(self):
 700        self.check_sendall_interrupted(True)
 701
 702    def testListenBacklog0(self):
 703        srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 704        srv.bind((HOST, 0))
 705        # backlog = 0
 706        srv.listen(0)
 707        srv.close()
 708
 709    @unittest.skipUnless(SUPPORTS_IPV6, 'IPv6 required for this test.')
 710    def test_flowinfo(self):
 711        self.assertRaises(OverflowError, socket.getnameinfo,
 712                          ('::1',0, 0xffffffff), 0)
 713        s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
 714        try:
 715            self.assertRaises(OverflowError, s.bind, ('::1', 0, -10))
 716        finally:
 717            s.close()
 718
 719
 720@unittest.skipUnless(thread, 'Threading required for this test.')
 721class BasicTCPTest(SocketConnectedTest):
 722
 723    def __init__(self, methodName='runTest'):
 724        SocketConnectedTest.__init__(self, methodName=methodName)
 725
 726    def testRecv(self):
 727        # Testing large receive over TCP
 728        msg = self.cli_conn.recv(1024)
 729        self.assertEqual(msg, MSG)
 730
 731    def _testRecv(self):
 732        self.serv_conn.send(MSG)
 733
 734    def testOverFlowRecv(self):
 735        # Testing receive in chunks over TCP
 736        seg1 = self.cli_conn.recv(len(MSG) - 3)
 737        seg2 = self.cli_conn.recv(1024)
 738        msg = seg1 + seg2
 739        self.assertEqual(msg, MSG)
 740
 741    def _testOverFlowRecv(self):
 742        self.serv_conn.send(MSG)
 743
 744    def testRecvFrom(self):
 745        # Testing large recvfrom() over TCP
 746        msg, addr = self.cli_conn.recvfrom(1024)
 747        self.assertEqual(msg, MSG)
 748
 749    def _testRecvFrom(self):
 750        self.serv_conn.send(MSG)
 751
 752    def testOverFlowRecvFrom(self):
 753        # Testing recvfrom() in chunks over TCP
 754        seg1, addr = self.cli_conn.recvfrom(len(MSG)-3)
 755        seg2, addr = self.cli_conn.recvfrom(1024)
 756        msg = seg1 + seg2
 757        self.assertEqual(msg, MSG)
 758
 759    def _testOverFlowRecvFrom(self):
 760        self.serv_conn.send(MSG)
 761
 762    def testSendAll(self):
 763        # Testing sendall() with a 2048 byte string over TCP
 764        msg = ''
 765        while 1:
 766            read = self.cli_conn.recv(1024)
 767            if not read:
 768                break
 769            msg += read
 770        self.assertEqual(msg, 'f' * 2048)
 771
 772    def _testSendAll(self):
 773        big_chunk = 'f' * 2048
 774        self.serv_conn.sendall(big_chunk)
 775
 776    def testFromFd(self):
 777        # Testing fromfd()
 778        if not hasattr(socket, "fromfd"):
 779            return # On Windows, this doesn't exist
 780        fd = self.cli_conn.fileno()
 781        sock = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
 782        self.addCleanup(sock.close)
 783        msg = sock.recv(1024)
 784        self.assertEqual(msg, MSG)
 785
 786    def _testFromFd(self):
 787        self.serv_conn.send(MSG)
 788
 789    def testDup(self):
 790        # Testing dup()
 791        sock = self.cli_conn.dup()
 792        self.addCleanup(sock.close)
 793        msg = sock.recv(1024)
 794        self.assertEqual(msg, MSG)
 795
 796    def _testDup(self):
 797        self.serv_conn.send(MSG)
 798
 799    def testShutdown(self):
 800        # Testing shutdown()
 801        msg = self.cli_conn.recv(1024)
 802        self.assertEqual(msg, MSG)
 803        # wait for _testShutdown to finish: on OS X, when the server
 804        # closes the connection the client also becomes disconnected,
 805        # and the client's shutdown call will fail. (Issue #4397.)
 806        self.done.wait()
 807
 808    def _testShutdown(self):
 809        self.serv_conn.send(MSG)
 810        self.serv_conn.shutdown(2)
 811
 812@unittest.skipUnless(thread, 'Threading required for this test.')
 813class BasicUDPTest(ThreadedUDPSocketTest):
 814
 815    def __init__(self, methodName='runTest'):
 816        ThreadedUDPSocketTest.__init__(self, methodName=methodName)
 817
 818    def testSendtoAndRecv(self):
 819        # Testing sendto() and Recv() over UDP
 820        msg = self.serv.recv(len(MSG))
 821        self.assertEqual(msg, MSG)
 822
 823    def _testSendtoAndRecv(self):
 824        self.cli.sendto(MSG, 0, (HOST, self.port))
 825
 826    def testRecvFrom(self):
 827        # Testing recvfrom() over UDP
 828        msg, addr = self.serv.recvfrom(len(MSG))
 829        self.assertEqual(msg, MSG)
 830
 831    def _testRecvFrom(self):
 832        self.cli.sendto(MSG, 0, (HOST, self.port))
 833
 834    def testRecvFromNegative(self):
 835        # Negative lengths passed to recvfrom should give ValueError.
 836        self.assertRaises(ValueError, self.serv.recvfrom, -1)
 837
 838    def _testRecvFromNegative(self):
 839        self.cli.sendto(MSG, 0, (HOST, self.port))
 840
 841@unittest.skipUnless(thread, 'Threading required for this test.')
 842class TCPCloserTest(ThreadedTCPSocketTest):
 843
 844    def testClose(self):
 845        conn, addr = self.serv.accept()
 846        conn.close()
 847
 848        sd = self.cli
 849        read, write, err = select.select([sd], [], [], 1.0)
 850        self.assertEqual(read, [sd])
 851        self.assertEqual(sd.recv(1), '')
 852
 853    def _testClose(self):
 854        self.cli.connect((HOST, self.port))
 855        time.sleep(1.0)
 856
 857@unittest.skipUnless(thread, 'Threading required for this test.')
 858class BasicSocketPairTest(SocketPairTest):
 859
 860    def __init__(self, methodName='runTest'):
 861        SocketPairTest.__init__(self, methodName=methodName)
 862
 863    def testRecv(self):
 864        msg = self.serv.recv(1024)
 865        self.assertEqual(msg, MSG)
 866
 867    def _testRecv(self):
 868        self.cli.send(MSG)
 869
 870    def testSend(self):
 871        self.serv.send(MSG)
 872
 873    def _testSend(self):
 874        msg = self.cli.recv(1024)
 875        self.assertEqual(msg, MSG)
 876
 877@unittest.skipUnless(thread, 'Threading required for this test.')
 878class NonBlockingTCPTests(ThreadedTCPSocketTest):
 879
 880    def __init__(self, methodName='runTest'):
 881        ThreadedTCPSocketTest.__init__(self, methodName=methodName)
 882
 883    def testSetBlocking(self):
 884        # Testing whether set blocking works
 885        self.serv.setblocking(0)
 886        start = time.time()
 887        try:
 888            self.serv.accept()
 889        except socket.error:
 890            pass
 891        end = time.time()
 892        self.assertTrue((end - start) < 1.0, "Error setting non-blocking mode.")
 893
 894    def _testSetBlocking(self):
 895        pass
 896
 897    def testAccept(self):
 898        # Testing non-blocking accept
 899        self.serv.setblocking(0)
 900        try:
 901            conn, addr = self.serv.accept()
 902        except socket.error:
 903            pass
 904        else:
 905            self.fail("Error trying to do non-blocking accept.")
 906        read, write, err = select.select([self.serv], [], [])
 907        if self.serv in read:
 908            conn, addr = self.serv.accept()
 909            conn.close()
 910        else:
 911            self.fail("Error trying to do accept after select.")
 912
 913    def _testAccept(self):
 914        time.sleep(0.1)
 915        self.cli.connect((HOST, self.port))
 916
 917    def testConnect(self):
 918        # Testing non-blocking connect
 919        conn, addr = self.serv.accept()
 920        conn.close()
 921
 922    def _testConnect(self):
 923        self.cli.settimeout(10)
 924        self.cli.connect((HOST, self.port))
 925
 926    def testRecv(self):
 927        # Testing non-blocking recv
 928        conn, addr = self.serv.accept()
 929        conn.setblocking(0)
 930        try:
 931            msg = conn.recv(len(MSG))
 932        except socket.error:
 933            pass
 934        else:
 935            self.fail("Error trying to do non-blocking recv.")
 936        read, write, err = select.select([conn], [], [])
 937        if conn in read:
 938            msg = conn.recv(len(MSG))
 939            conn.close()
 940            self.assertEqual(msg, MSG)
 941        else:
 942            self.fail("Error during select call to non-blocking socket.")
 943
 944    def _testRecv(self):
 945        self.cli.connect((HOST, self.port))
 946        time.sleep(0.1)
 947        self.cli.send(MSG)
 948
 949@unittest.skipUnless(thread, 'Threading required for this test.')
 950class FileObjectClassTestCase(SocketConnectedTest):
 951
 952    bufsize = -1 # Use default buffer size
 953
 954    def __init__(self, methodName='runTest'):
 955        SocketConnectedTest.__init__(self, methodName=methodName)
 956
 957    def setUp(self):
 958        SocketConnectedTest.setUp(self)
 959        self.serv_file = self.cli_conn.makefile('rb', self.bufsize)
 960
 961    def tearDown(self):
 962        self.serv_file.close()
 963        self.assertTrue(self.serv_file.closed)
 964        self.serv_file = None
 965        SocketConnectedTest.tearDown(self)
 966
 967    def clientSetUp(self):
 968        SocketConnectedTest.clientSetUp(self)
 969        self.cli_file = self.serv_conn.makefile('wb')
 970
 971    def clientTearDown(self):
 972        self.cli_file.close()
 973        self.assertTrue(self.cli_file.closed)
 974        self.cli_file = None
 975        SocketConnectedTest.clientTearDown(self)
 976
 977    def testSmallRead(self):
 978        # Performing small file read test
 979        first_seg = self.serv_file.read(len(MSG)-3)
 980        second_seg = self.serv_file.read(3)
 981        msg = first_seg + second_seg
 982        self.assertEqual(msg, MSG)
 983
 984    def _testSmallRead(self):
 985        self.cli_file.write(MSG)
 986        self.cli_file.flush()
 987
 988    def testFullRead(self):
 989        # read until EOF
 990        msg = self.serv_file.read()
 991        self.assertEqual(msg, MSG)
 992
 993    def _testFullRead(self):
 994        self.cli_file.write(MSG)
 995        self.cli_file.close()
 996
 997    def testUnbufferedRead(self):
 998        # Performing unbuffered file read test
 999        buf = ''
1000        while 1:
1001            char = self.serv_file.read(1)
1002            if not char:
1003                break
1004            buf += char
1005        self.assertEqual(buf, MSG)
1006
1007    def _testUnbufferedRead(self):
1008        self.cli_file.write(MSG)
1009        self.cli_file.flush()
1010
1011    def testReadline(self):
1012        # Performing file readline test
1013        line = self.serv_file.readline()
1014        self.assertEqual(line, MSG)
1015
1016    def _testReadline(self):
1017        self.cli_file.write(MSG)
1018        self.cli_file.flush()
1019
1020    def testReadlineAfterRead(self):
1021        a_baloo_is = self.serv_file.read(len("A baloo is"))
1022        self.assertEqual("A baloo is", a_baloo_is)
1023        _a_bear = self.serv_file.read(len(" a bear"))
1024        self.assertEqual(" a bear", _a_bear)
1025        line = self.serv_file.readline()
1026        self.assertEqual("\n", line)
1027        line = self.serv_file.readline()
1028        self.assertEqual("A BALOO IS A BEAR.\n", line)
1029        line = self.serv_file.readline()
1030        self.assertEqual(MSG, line)
1031
1032    def _testReadlineAfterRead(self):
1033        self.cli_file.write("A baloo is a bear\n")
1034        self.cli_file.write("A BALOO IS A BEAR.\n")
1035        self.cli_file.write(MSG)
1036        self.cli_file.flush()
1037
1038    def testReadlineAfterReadNoNewline(self):
1039        end_of_ = self.serv_file.read(len("End Of "))
1040        self.assertEqual("End Of ", end_of_)
1041        line = self.serv_file.readline()
1042        self.assertEqual("Line", line)
1043
1044    def _testReadlineAfterReadNoNewline(self):
1045        self.cli_file.write("End Of Line")
1046
1047    def testClosedAttr(self):
1048        self.assertTrue(not self.serv_file.closed)
1049
1050    def _testClosedAttr(self):
1051        self.assertTrue(not self.cli_file.closed)
1052
1053
1054class FileObjectInterruptedTestCase(unittest.TestCase):
1055    """Test that the file object correctly handles EINTR internally."""
1056
1057    class MockSocket(object):
1058        def __init__(self, recv_funcs=()):
1059            # A generator that returns callables that we'll call for each
1060            # call to recv().
1061            self._recv_step = iter(recv_funcs)
1062
1063        def recv(self, size):
1064            return self._recv_step.next()()
1065
1066    @staticmethod
1067    def _raise_eintr():
1068        raise socket.error(errno.EINTR)
1069
1070    def _test_readline(self, size=-1, **kwargs):
1071        mock_sock = self.MockSocket(recv_funcs=[
1072                lambda : "This is the first line\nAnd the sec",
1073                self._raise_eintr,
1074                lambda : "ond line is here\n",
1075                lambda : "",
1076            ])
1077        fo = socket._fileobject(mock_sock, **kwargs)
1078        self.assertEqual(fo.readline(size), "This is the first line\n")
1079        self.assertEqual(fo.readline(size), "And the second line is here\n")
1080
1081    def _test_read(self, size=-1, **kwargs):
1082        mock_sock = self.MockSocket(recv_funcs=[
1083                lambda : "This is the first line\nAnd the sec",
1084                self._raise_eintr,
1085                lambda : "ond line is here\n",
1086                lambda : "",
1087            ])
1088        fo = socket._fileobject(mock_sock, **kwargs)
1089        self.assertEqual(fo.read(size), "This is the first line\n"
1090                          "And the second line is here\n")
1091
1092    def test_default(self):
1093        self._test_readline()
1094        self._test_readline(size=100)
1095        self._test_read()
1096        self._test_read(size=100)
1097
1098    def test_with_1k_buffer(self):
1099        self._test_readline(bufsize=1024)
1100        self._test_readline(size=100, bufsize=1024)
1101        self._test_read(bufsize=1024)
1102        self._test_read(size=100, bufsize=1024)
1103
1104    def _test_readline_no_buffer(self, size=-1):
1105        mock_sock = self.MockSocket(recv_funcs=[
1106                lambda : "aa",
1107                lambda : "\n",
1108                lambda : "BB",
1109                self._raise_eintr,
1110                lambda : "bb",
1111                lambda : "",
1112            ])
1113        fo = socket._fileobject(mock_sock, bufsize=0)
1114        self.assertEqual(fo.readline(size), "aa\n")
1115        self.assertEqual(fo.readline(size), "BBbb")
1116
1117    def test_no_buffer(self):
1118        self._test_readline_no_buffer()
1119        self._test_readline_no_buffer(size=4)
1120        self._test_read(bufsize=0)
1121        self._test_read(size=100, bufsize=0)
1122
1123
1124class UnbufferedFileObjectClassTestCase(FileObjectClassTestCase):
1125
1126    """Repeat the tests from FileObjectClassTestCase with bufsize==0.
1127
1128    In this case (and in this case only), it should be possible to
1129    create a file object, read a line from it, create another file
1130    object, read another line from it, without loss of data in the
1131    first file object's buffer.  Note that httplib relies on this
1132    when reading multiple requests from the same socket."""
1133
1134    bufsize = 0 # Use unbuffered mode
1135
1136    def testUnbufferedReadline(self):
1137        # Read a line, create a new file object, read another line with it
1138        line = self.serv_file.readline() # first line
1139        self.assertEqual(line, "A. " + MSG) # first line
1140        self.serv_file = self.cli_conn.makefile('rb', 0)
1141        line = self.serv_file.readline() # second line
1142        self.assertEqual(line, "B. " + MSG) # second line
1143
1144    def _testUnbufferedReadline(self):
1145        self.cli_file.write("A. " + MSG)
1146        self.cli_file.write("B. " + MSG)
1147        self.cli_file.flush()
1148
1149class LineBufferedFileObjectClassTestCase(FileObjectClassTestCase):
1150
1151    bufsize = 1 # Default-buffered for reading; line-buffered for writing
1152
1153
1154class SmallBufferedFileObjectClassTestCase(FileObjectClassTestCase):
1155
1156    bufsize = 2 # Exercise the buffering code
1157
1158
1159class NetworkConnectionTest(object):
1160    """Prove network connection."""
1161    def clientSetUp(self):
1162        # We're inherited below by BasicTCPTest2, which also inherits
1163        # BasicTCPTest, which defines self.port referenced below.
1164        self.cli = socket.create_connection((HOST, self.port))
1165        self.serv_conn = self.cli
1166
1167class BasicTCPTest2(NetworkConnectionTest, BasicTCPTest):
1168    """Tests that NetworkConnection does not break existing TCP functionality.
1169    """
1170
1171class NetworkConnectionNoServer(unittest.TestCase):
1172    class MockSocket(socket.socket):
1173        def connect(self, *args):
1174            raise socket.timeout('timed out')
1175
1176    @contextlib.contextmanager
1177    def mocked_socket_module(self):
1178        """Return a socket which times out on connect"""
1179        old_socket = socket.socket
1180        socket.socket = self.MockSocket
1181        try:
1182            yield
1183        finally:
1184            socket.socket = old_socket
1185
1186    def test_connect(self):
1187        port = test_support.find_unused_port()
1188        cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1189        self.addCleanup(cli.close)
1190        with self.assertRaises(socket.error) as cm:
1191            cli.connect((HOST, port))
1192        self.assertEqual(cm.exception.errno, errno.ECONNREFUSED)
1193
1194    def test_create_connection(self):
1195        # Issue #9792: errors raised by create_connection() should have
1196        # a proper errno attribute.
1197        port = test_support.find_unused_port()
1198        with self.assertRaises(socket.error) as cm:
1199            socket.create_connection((HOST, port))
1200        self.assertEqual(cm.exception.errno, errno.ECONNREFUSED)
1201
1202    def test_create_connection_timeout(self):
1203        # Issue #9792: create_connection() should not recast timeout errors
1204        # as generic socket errors.
1205        with self.mocked_socket_module():
1206            with self.assertRaises(socket.timeout):
1207                socket.create_connection((HOST, 1234))
1208
1209
1210@unittest.skipUnless(thread, 'Threading required for this test.')
1211class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest):
1212
1213    def __init__(self, methodName='runTest'):
1214        SocketTCPTest.__init__(self, methodName=methodName)
1215        ThreadableTest.__init__(self)
1216
1217    def clientSetUp(self):
1218        self.source_port = test_support.find_unused_port()
1219
1220    def clientTearDown(self):
1221        self.cli.close()
1222        self.cli = None
1223        ThreadableTest.clientTearDown(self)
1224
1225    def _justAccept(self):
1226        conn, addr = self.serv.accept()
1227        conn.close()
1228
1229    testFamily = _justAccept
1230    def _testFamily(self):
1231        self.cli = socket.create_connection((HOST, self.port), timeout=30)
1232        self.addCleanup(self.cli.close)
1233        self.assertEqual(self.cli.family, 2)
1234
1235    testSourceAddress = _justAccept
1236    def _testSourceAddress(self):
1237        self.cli = socket.create_connection((HOST, self.port), timeout=30,
1238                source_address=('', self.source_port))
1239        self.addCleanup(self.cli.close)
1240        self.assertEqual(self.cli.getsockname()[1], self.source_port)
1241        # The port number being used is sufficient to show that the bind()
1242        # call happened.
1243
1244    testTimeoutDefault = _justAccept
1245    def _testTimeoutDefault(self):
1246        # passing no explicit timeout uses socket's global default
1247        self.assertTrue(socket.getdefaulttimeout() is None)
1248        socket.setdefaulttimeout(42)
1249        try:
1250            self.cli = socket.create_connection((HOST, self.port))
1251            self.addCleanup(self.cli.close)
1252        finally:
1253            socket.setdefaulttimeout(None)
1254        self.assertEqual(self.cli.gettimeout(), 42)
1255
1256    testTimeoutNone = _justAccept
1257    def _testTimeoutNone(self):
1258        # None timeout means the same as sock.settimeout(None)
1259        self.assertTrue(socket.getdefaulttimeout() is None)
1260        socket.setdefaulttimeout(30)
1261        try:
1262            self.cli = socket.create_connection((HOST, self.port), timeout=None)
1263            self.addCleanup(self.cli.close)
1264        finally:
1265            socket.setdefaulttimeout(None)
1266        self.assertEqual(self.cli.gettimeout(), None)
1267
1268    testTimeoutValueNamed = _justAccept
1269    def _testTimeoutValueNamed(self):
1270        self.cli = socket.create_connection((HOST, self.port), timeout=30)
1271        self.assertEqual(self.cli.gettimeout(), 30)
1272
1273    testTimeoutValueNonamed = _justAccept
1274    def _testTimeoutValueNonamed(self):
1275        self.cli = socket.create_connection((HOST, self.port), 30)
1276        self.addCleanup(self.cli.close)
1277        self.assertEqual(self.cli.gettimeout(), 30)
1278
1279@unittest.skipUnless(thread, 'Threading required for this test.')
1280class NetworkConnectionBehaviourTest(SocketTCPTest, ThreadableTest):
1281
1282    def __init__(self, methodName='runTest'):
1283        SocketTCPTest.__init__(self, methodName=methodName)
1284        ThreadableTest.__init__(self)
1285
1286    def clientSetUp(self):
1287        pass
1288
1289    def clientTearDown(self):
1290        self.cli.close()
1291        self.cli = None
1292        ThreadableTest.clientTearDown(self)
1293
1294    def testInsideTimeout(self):
1295        conn, addr = self.serv.accept()
1296        self.addCleanup(conn.close)
1297        time.sleep(3)
1298        conn.send("done!")
1299    testOutsideTimeout = testInsideTimeout
1300
1301    def _testInsideTimeout(self):
1302        self.cli = sock = socket.create_connection((HOST, self.port))
1303        data = sock.recv(5)
1304        self.assertEqual(data, "done!")
1305
1306    def _testOutsideTimeout(self):
1307        self.cli = sock = socket.create_connection((HOST, self.port), timeout=1)
1308        self.assertRaises(socket.timeout, lambda: sock.recv(5))
1309
1310
1311class Urllib2FileobjectTest(unittest.TestCase):
1312
1313    # urllib2.HTTPHandler has "borrowed" socket._fileobject, and requires that
1314    # it close the socket if the close c'tor argument is true
1315
1316    def testClose(self):
1317        class MockSocket:
1318            closed = False
1319            def flush(self): pass
1320            def close(self): self.closed = True
1321
1322        # must not close unless we request it: the original use of _fileobject
1323        # by module socket requires that the underlying socket not be closed until
1324        # the _socketobject that created the _fileobject is closed
1325        s = MockSocket()
1326        f = socket._fileobject(s)
1327        f.close()
1328        self.assertTrue(not s.closed)
1329
1330        s = MockSocket()
1331        f = socket._fileobject(s, close=True)
1332        f.close()
1333        self.assertTrue(s.closed)
1334
1335class TCPTimeoutTest(SocketTCPTest):
1336
1337    def testTCPTimeout(self):
1338        def raise_timeout(*args, **kwargs):
1339            self.serv.settimeout(1.0)
1340            self.serv.accept()
1341        self.assertRaises(socket.timeout, raise_timeout,
1342                              "Error generating a timeout exception (TCP)")
1343
1344    def testTimeoutZero(self):
1345        ok = False
1346        try:
1347            self.serv.settimeout(0.0)
1348            foo = self.serv.accept()
1349        except socket.timeout:
1350            self.fail("caught timeout instead of error (TCP)")
1351        except socket.error:
1352            ok = True
1353        except:
1354            self.fail("caught unexpected exception (TCP)")
1355        if not ok:
1356            self.fail("accept() returned success when we did not expect it")
1357
1358    def testInterruptedTimeout(self):
1359        # XXX I don't know how to do this test on MSWindows or any other
1360        # plaform that doesn't support signal.alarm() or os.kill(), though
1361        # the bug should have existed on all platforms.
1362        if not hasattr(signal, "alarm"):
1363            return                  # can only test on *nix
1364        self.serv.settimeout(5.0)   # must be longer than alarm
1365        class Alarm(Exception):
1366            pass
1367        def alarm_handler(signal, frame):
1368            raise Alarm
1369        old_alarm = signal.signal(signal.SIGALRM, alarm_handler)
1370        try:
1371            signal.alarm(2)    # POSIX allows alarm to be up to 1 second early
1372            try:
1373                foo = self.serv.accept()
1374            except socket.timeout:
1375                self.fail("caught timeout instead of Alarm")
1376            except Alarm:
1377                pass
1378            except:
1379                self.fail("caught other exception instead of Alarm:"
1380                          " %s(%s):\n%s" %
1381                          (sys.exc_info()[:2] + (traceback.format_exc(),)))
1382            else:
1383                self.fail("nothing caught")
1384            finally:
1385                signal.alarm(0)         # shut off alarm
1386        except Alarm:
1387            self.fail("got Alarm in wrong place")
1388        finally:
1389            # no alarm can be pending.  Safe to restore old handler.
1390            signal.signal(signal.SIGALRM, old_alarm)
1391
1392class UDPTimeoutTest(SocketUDPTest):
1393
1394    def tes

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