PageRenderTime 19ms CodeModel.GetById 4ms app.highlight 74ms RepoModel.GetById 1ms app.codeStats 1ms

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

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

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