def test_del_closes_socket (self):

        def accept_once (listener):
            # delete/overwrite the original conn
            # object, only keeping the file object around
            # closing the file object should close everything
            try:
                conn, addr = listener.accept()
                conn = conn.makefile('w')
                conn.write('hello\n')
                conn.close()
                self.assertWriteToClosedFileRaises(conn)
            finally:
                listener.close()

        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        server.bind(('127.0.0.1', 0))
        server.listen(50)
        killer = spawn(accept_once, server)

        client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        client.connect(('127.0.0.1', server.getsockname()[1]))
        fd = client.makefile()
        client.close()

        assert fd.read() == 'hello\n'
        assert fd.read() == ''

        killer.wait()
Beispiel #2
0
    def test_default_timeout(self):
        # Testing default timeout
        # The default timeout should initially be None
        self.assertEqual(socket.getdefaulttimeout(), None)
        s = socket.socket()
        self.assertEqual(s.gettimeout(), None)
        s.close()

        # Set the default timeout to 10, and see if it propagates
        socket.setdefaulttimeout(10)
        self.assertEqual(socket.getdefaulttimeout(), 10)
        s = socket.socket()
        self.assertEqual(s.gettimeout(), 10)
        s.close()

        # Reset the default timeout to None, and see if it propagates
        socket.setdefaulttimeout(None)
        self.assertEqual(socket.getdefaulttimeout(), None)
        s = socket.socket()
        self.assertEqual(s.gettimeout(), None)
        s.close()

        # Check that setting it to an invalid value raises ValueError
        self.assertRaises(ValueError, socket.setdefaulttimeout, -1)

        # Check that setting it to an invalid type raises TypeError
        self.assertRaises(TypeError, socket.setdefaulttimeout, "spam")
Beispiel #3
0
    def test_default_timeout (self):
        # Testing default timeout
        # The default timeout should initially be None
        self.assertEqual(socket.getdefaulttimeout(), None)
        s = socket.socket()
        self.assertEqual(s.gettimeout(), None)
        s.close()

        # Set the default timeout to 10, and see if it propagates
        socket.setdefaulttimeout(10)
        self.assertEqual(socket.getdefaulttimeout(), 10)
        s = socket.socket()
        self.assertEqual(s.gettimeout(), 10)
        s.close()

        # Reset the default timeout to None, and see if it propagates
        socket.setdefaulttimeout(None)
        self.assertEqual(socket.getdefaulttimeout(), None)
        s = socket.socket()
        self.assertEqual(s.gettimeout(), None)
        s.close()

        # Check that setting it to an invalid value raises ValueError
        self.assertRaises(ValueError, socket.setdefaulttimeout, -1)

        # Check that setting it to an invalid type raises TypeError
        self.assertRaises(TypeError, socket.setdefaulttimeout, "spam")
    def test_close_with_makefile (self):
        def accept_close_early (listener):
            # verify that the makefile and the socket are truly independent
            # by closing the socket prior to using the made file
            try:
                conn, addr = listener.accept()
                fd = conn.makefile('w')
                conn.close()
                fd.write('hello\n')
                fd.close()
                self.assertWriteToClosedFileRaises(fd)
                self.assertRaises(socket.error, conn.send, s2b('b'))
            finally:
                listener.close()

        def accept_close_late (listener):
            # verify that the makefile and the socket are truly independent
            # by closing the made file and then sending a character
            try:
                conn, addr = listener.accept()
                fd = conn.makefile('w')
                fd.write('hello')
                fd.close()
                conn.send(s2b('\n'))
                conn.close()
                self.assertWriteToClosedFileRaises(fd)
                self.assertRaises(socket.error, conn.send, s2b('b'))
            finally:
                listener.close()

        def did_it_work (server):
            client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            _, port = server.getsockname()
            print 'connecting to port', port
            client.connect(('127.0.0.1', port))
            fd = client.makefile()
            client.close()
            assert fd.readline() == 'hello\n'
            assert fd.read() == ''
            fd.close()

        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        server.bind(('0.0.0.0', 61222))
        self.assertEqual(server.getsockname()[1], 61222)
        server.listen(50)
        killer = spawn(accept_close_early, server)
        did_it_work(server)
        killer.wait()

        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        server.bind(('0.0.0.0', 0))
        server.listen(50)
        killer = spawn(accept_close_late, server)
        did_it_work(server)
        killer.wait()
Beispiel #5
0
 def testLinuxAbstractNamespace (self):
     address = "\x00python-test-hello\x00\xff"
     s1 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
     s1.bind(address)
     s1.listen(1)
     s2 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
     s2.connect(s1.getsockname())
     s1.accept()
     self.assertEqual(s1.getsockname(), address)
     self.assertEqual(s2.getpeername(), address)
Beispiel #6
0
 def testLinuxAbstractNamespace(self):
     address = "\x00python-test-hello\x00\xff"
     s1 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
     s1.bind(address)
     s1.listen(1)
     s2 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
     s2.connect(s1.getsockname())
     s1.accept()
     self.assertEqual(s1.getsockname(), address)
     self.assertEqual(s2.getpeername(), address)
Beispiel #7
0
def geturl (url):
    c = socket.socket()
    ip = socket.gethostbyname(url)
    c.connect((ip, 80))
    print '%s connected' % url
    c.sendall('GET /\r\n\r\n')
    return c.recv(1024)
Beispiel #8
0
def init_server ():
    s = socket.socket()
    s.settimeout(SOCKET_TIMEOUT)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(('localhost', 0))
    s.listen(5)
    return s, s.getsockname()[1]
Beispiel #9
0
 def test_set_sock_opt (self):
     # Testing setsockopt()
     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.addCleanup(sock.close)
     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
     reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
     self.assertFalse(reuse == 0, "failed to set reuse mode")
Beispiel #10
0
 def test_set_sock_opt(self):
     # Testing setsockopt()
     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.addCleanup(sock.close)
     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
     reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
     self.assertFalse(reuse == 0, "failed to set reuse mode")
Beispiel #11
0
 def test_get_sock_opt(self):
     # Testing getsockopt()
     # We know a socket should start without reuse==0
     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.addCleanup(sock.close)
     reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
     self.assertFalse(reuse != 0, "initial mode is reuse")
Beispiel #12
0
    def test_timeout (self, socket = socket):
        """
        Test that the socket timeout exception works correctly.
        """
        server = sockets.GreenSocket(socket.AF_INET, socket.SOCK_STREAM)
        server.bind(('127.0.0.1', 0))
        server.listen(1)
        _, port = server.getsockname()
        self.assertNotEqual(port, 0)

        s = socket.socket()

        s.connect(('127.0.0.1', port))

        cs, addr = server.accept()
        cs.settimeout(1)
        try:
            try:
                cs.recv(1024)
                self.fail("Should have timed out")
            except socket.timeout, ex:
                assert hasattr(ex, 'args')
                assert len(ex.args) == 1
                assert ex.args[0] == 'timed out'
        finally:
            s.close()
            cs.close()
            server.close()
Beispiel #13
0
def launch_heavy_threads ():
    import threading
    import socket

    def heavy_accepter (server_sock, pool):
        import threading
        for i in xrange(CONCURRENCY):
            sock, addr = server_sock.accept()
            t = threading.Thread(None, reader, "reader thread", (sock,))
            t.start()
            pool.append(t)

    threads = []
    server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_sock.bind(('localhost', 0))
    server_sock.listen(50)
    addr = ('localhost', server_sock.getsockname()[1])
    accepter_thread = threading.Thread(None, heavy_accepter, "accepter thread",
        (server_sock, threads))
    accepter_thread.start()
    threads.append(accepter_thread)
    for i in xrange(CONCURRENCY):
        client_thread = threading.Thread(None, writer, "writer thread", (addr, socket.socket))
        client_thread.start()
        threads.append(client_thread)
    for t in threads:
        t.join()
Beispiel #14
0
def geturl(url):
    c = socket.socket()
    ip = socket.gethostbyname(url)
    c.connect((ip, 80))
    print '%s connected' % url
    c.sendall('GET /\r\n\r\n')
    return c.recv(1024)
    def test_timeout(self, socket=socket):
        """
        Test that the socket timeout exception works correctly.
        """
        server = sockets.GreenSocket(socket.AF_INET, socket.SOCK_STREAM)
        server.bind(('127.0.0.1', 0))
        server.listen(1)
        _, port = server.getsockname()
        self.assertNotEqual(port, 0)

        s = socket.socket()

        s.connect(('127.0.0.1', port))

        cs, addr = server.accept()
        cs.settimeout(1)
        try:
            try:
                cs.recv(1024)
                self.fail("Should have timed out")
            except socket.timeout, ex:
                assert hasattr(ex, 'args')
                assert len(ex.args) == 1
                assert ex.args[0] == 'timed out'
        finally:
            s.close()
            cs.close()
            server.close()
Beispiel #16
0
 def test_connect(self):
     port = test_support.find_unused_port()
     cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.addCleanup(cli.close)
     with self.assertRaises(socket.error) as cm:
         cli.connect((HOST, port))
     self.assertEqual(cm.exception.errno, errno.ECONNREFUSED)
Beispiel #17
0
 def test_connect (self):
     port = test_support.find_unused_port()
     cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.addCleanup(cli.close)
     with self.assertRaises(socket.error) as cm:
         cli.connect((HOST, port))
     self.assertEqual(cm.exception.errno, errno.ECONNREFUSED)
Beispiel #18
0
 def test_new_attributes (self):
     # testing .family, .type and .protocol
     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.assertEqual(sock.family, socket.AF_INET)
     self.assertEqual(sock.type, socket.SOCK_STREAM)
     self.assertEqual(sock.proto, 0)
     sock.close()
Beispiel #19
0
 def test_new_attributes(self):
     # testing .family, .type and .protocol
     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.assertEqual(sock.family, socket.AF_INET)
     self.assertEqual(sock.type, socket.SOCK_STREAM)
     self.assertEqual(sock.proto, 0)
     sock.close()
Beispiel #20
0
 def test_get_sock_opt (self):
     # Testing getsockopt()
     # We know a socket should start without reuse==0
     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.addCleanup(sock.close)
     reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
     self.assertFalse(reuse != 0, "initial mode is reuse")
Beispiel #21
0
    def testRDM (self):
        srv = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
        cli = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)

        srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
                   TIPC_LOWER, TIPC_UPPER)
        srv.bind(srvaddr)

        sendaddr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
                    TIPC_LOWER + (TIPC_UPPER - TIPC_LOWER) / 2, 0)
        cli.sendto(MSG, sendaddr)

        msg, recvaddr = srv.recvfrom(1024)

        self.assertEqual(cli.getsockname(), recvaddr)
        self.assertEqual(msg, MSG)
Beispiel #22
0
    def testRDM(self):
        srv = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)
        cli = socket.socket(socket.AF_TIPC, socket.SOCK_RDM)

        srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE, TIPC_LOWER,
                   TIPC_UPPER)
        srv.bind(srvaddr)

        sendaddr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
                    TIPC_LOWER + (TIPC_UPPER - TIPC_LOWER) / 2, 0)
        cli.sendto(MSG, sendaddr)

        msg, recvaddr = srv.recvfrom(1024)

        self.assertEqual(cli.getsockname(), recvaddr)
        self.assertEqual(msg, MSG)
Beispiel #23
0
 def dgram_examine (self, proto, addr):
     s = socket.socket(proto, socket.SOCK_DGRAM)
     s.sendto(TEST_STR, addr)
     buf = data = receive(s, 100)
     while data and '\n' not in buf:
         data = receive(s, 100)
         buf += data
     self.assertEqual(buf, TEST_STR)
     s.close()
Beispiel #24
0
def make_request (port):
    #print 'make_request'
    s = socket.socket()
    s.connect(('localhost', port))
    #print 'make_request - connected'
    res = s.send('hello')
    #print 'make_request - sent %s' % res
    res = s.recv(100)
    assert res == 'bye', repr(res)
Beispiel #25
0
 def setUp(self):
     self.srv = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
     self.srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
     srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE, TIPC_LOWER,
                TIPC_UPPER)
     self.srv.bind(srvaddr)
     self.srv.listen(5)
     self.serverExplicitReady()
     self.conn, self.connaddr = self.srv.accept()
Beispiel #26
0
 def setUp (self):
     self.srv = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
     self.srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
     srvaddr = (socket.TIPC_ADDR_NAMESEQ, TIPC_STYPE,
                TIPC_LOWER, TIPC_UPPER)
     self.srv.bind(srvaddr)
     self.srv.listen(5)
     self.serverExplicitReady()
     self.conn, self.connaddr = self.srv.accept()
Beispiel #27
0
 def clientSetUp(self):
     # The is a hittable race between serverExplicitReady() and the
     # accept() call; sleep a little while to avoid it, otherwise
     # we could get an exception
     time.sleep(0.1)
     self.cli = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
     addr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
             TIPC_LOWER + (TIPC_UPPER - TIPC_LOWER) / 2, 0)
     self.cli.connect(addr)
     self.cliaddr = self.cli.getsockname()
Beispiel #28
0
 def did_it_work (server):
     client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     _, port = server.getsockname()
     print 'connecting to port', port
     client.connect(('127.0.0.1', port))
     fd = client.makefile()
     client.close()
     assert fd.readline() == 'hello\n'
     assert fd.read() == ''
     fd.close()
Beispiel #29
0
 def clientSetUp (self):
     # The is a hittable race between serverExplicitReady() and the
     # accept() call; sleep a little while to avoid it, otherwise
     # we could get an exception
     time.sleep(0.1)
     self.cli = socket.socket(socket.AF_TIPC, socket.SOCK_STREAM)
     addr = (socket.TIPC_ADDR_NAME, TIPC_STYPE,
             TIPC_LOWER + (TIPC_UPPER - TIPC_LOWER) / 2, 0)
     self.cli.connect(addr)
     self.cliaddr = self.cli.getsockname()
Beispiel #30
0
 def stream_examine (self, proto, addr):
     s = socket.socket(proto, socket.SOCK_STREAM)
     s.connect(addr)
     s.sendall(TEST_STR)
     buf = data = receive(s, 100)
     while data and '\n' not in buf:
         data = receive(s, 100)
         buf += data
     self.assertEqual(buf, TEST_STR)
     s.close()
Beispiel #31
0
 def test_wrap_socket (self):
     try:
         import ssl
     except ImportError:
         pass  # pre-2.6
     else:
         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
         sock.bind(('127.0.0.1', 0))
         sock.listen(50)
         ssl_sock = ssl.wrap_socket(sock)
Beispiel #32
0
def try_address (host, port = 0, family = socket.AF_INET):
    """Try to bind a socket on the given host:port and return True
    if that has been possible."""
    try:
        sock = socket.socket(family, socket.SOCK_STREAM)
        sock.bind((host, port))
    except (socket.error, socket.gaierror):
        return False
    else:
        sock.close()
        return True
Beispiel #33
0
def try_address(host, port=0, family=socket.AF_INET):
    """Try to bind a socket on the given host:port and return True
    if that has been possible."""
    try:
        sock = socket.socket(family, socket.SOCK_STREAM)
        sock.bind((host, port))
    except (socket.error, socket.gaierror):
        return False
    else:
        sock.close()
        return True
Beispiel #34
0
 def test_wrap_socket(self):
     try:
         import ssl
     except ImportError:
         pass  # pre-2.6
     else:
         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
         sock.bind(('127.0.0.1', 0))
         sock.listen(50)
         ssl_sock = ssl.wrap_socket(sock)
Beispiel #35
0
    def test_full_duplex (self):
        large_data = s2b('*') * 10 * min_buf_size()
        listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        listener.bind(('127.0.0.1', 0))
        listener.listen(50)

        def send_large (sock):
            sock.sendall(large_data)

        def read_large (sock):
            result = sock.recv(len(large_data))
            while len(result) < len(large_data):
                result += sock.recv(len(large_data))
                if result == '':
                    break
            self.assertEquals(result, large_data)

        def server ():
            (sock, addr) = listener.accept()
            sock = bufsized(sock)
            send_large_coro = spawn(send_large, sock)
            sleep(0)
            result = sock.recv(10)
            expected = s2b('hello world')
            while len(result) < len(expected) and result is not '':
                result += sock.recv(10)
            self.assertEquals(result, expected)
            send_large_coro.wait()

        server_evt = spawn(server)
        client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        client.connect(('127.0.0.1', listener.getsockname()[1]))
        bufsized(client)
        large_evt = spawn(read_large, client)
        sleep(0)
        client.sendall(s2b('hello world'))

        server_evt.wait()
        large_evt.wait()
        client.close()
Beispiel #36
0
    def test_full_duplex(self):
        large_data = s2b('*') * 10 * min_buf_size()
        listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        listener.bind(('127.0.0.1', 0))
        listener.listen(50)

        def send_large(sock):
            sock.sendall(large_data)

        def read_large(sock):
            result = sock.recv(len(large_data))
            while len(result) < len(large_data):
                result += sock.recv(len(large_data))
                if result == '':
                    break
            self.assertEquals(result, large_data)

        def server():
            (sock, addr) = listener.accept()
            sock = bufsized(sock)
            send_large_coro = spawn(send_large, sock)
            sleep(0)
            result = sock.recv(10)
            expected = s2b('hello world')
            while len(result) < len(expected) and result is not '':
                result += sock.recv(10)
            self.assertEquals(result, expected)
            send_large_coro.wait()

        server_evt = spawn(server)
        client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        client.connect(('127.0.0.1', listener.getsockname()[1]))
        bufsized(client)
        large_evt = spawn(read_large, client)
        sleep(0)
        client.sendall(s2b('hello world'))

        server_evt.wait()
        large_evt.wait()
        client.close()
Beispiel #37
0
 def test_getsockaddrarg (self):
     host = '0.0.0.0'
     port = 34555
     big_port = port + 65536
     neg_port = port - 65536
     sock = socket.socket()
     try:
         self.assertRaises(OverflowError, sock.bind, (host, big_port))
         self.assertRaises(OverflowError, sock.bind, (host, neg_port))
         sock.bind((host, port))
     finally:
         sock.close()
Beispiel #38
0
 def test_weakref (self):
     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     p = proxy(s)
     self.assertEqual(p.fileno(), s.fileno())
     s.close()
     s = None
     try:
         p.fileno()
     except ReferenceError:
         pass
     else:
         self.fail('Socket proxy still exists')
Beispiel #39
0
 def test_getsockaddrarg(self):
     host = '0.0.0.0'
     port = 34555
     big_port = port + 65536
     neg_port = port - 65536
     sock = socket.socket()
     try:
         self.assertRaises(OverflowError, sock.bind, (host, big_port))
         self.assertRaises(OverflowError, sock.bind, (host, neg_port))
         sock.bind((host, port))
     finally:
         sock.close()
Beispiel #40
0
 def test_server(self):
     listener = socket.socket()
     listener.bind(('localhost', 0))
     listener.listen(50)
     serv = evy.spawn(backdoor.backdoor_server, listener)
     client = socket.socket()
     client.connect(('localhost', listener.getsockname()[1]))
     f = client.makefile('rw')
     self.assert_('Python' in f.readline())
     f.readline()  # build info
     f.readline()  # help info
     self.assert_('InteractiveConsole' in f.readline())
     self.assertEquals('>>> ', f.read(4))
     f.write('print("hi")\n')
     f.flush()
     self.assertEquals('hi\n', f.readline())
     self.assertEquals('>>> ', f.read(4))
     f.close()
     client.close()
     serv.kill()
     # wait for the console to discover that it's dead
     sleep(0.1)
Beispiel #41
0
    def test_timeout_and_final_write(self):
        """
        This test verifies that a write on a socket that we've stopped listening for doesn't
        result in an incorrect switch
        """
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        server.bind(('127.0.0.1', 0))
        server.listen(50)
        _, bound_port = server.getsockname()
        self.assertNotEqual(bound_port, 0)

        def sender(evt):
            s2, addr = server.accept()
            wrap_wfile = s2.makefile('w')

            sleep(0.02)
            wrap_wfile.write('hi')
            s2.close()
            evt.send('sent via event')

        from evy import event

        evt = event.Event()
        spawn(sender, evt)
        sleep(0)  # lets the socket enter accept mode, which
        # is necessary for connect to succeed on windows
        try:
            # try and get some data off of this pipe
            # but bail before any is sent
            Timeout(0.01)
            client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            client.connect(('127.0.0.1', bound_port))
            wrap_rfile = client.makefile()
            _c = wrap_rfile.read(1)
            self.fail()
        except socket.error, e:
            self.fail('could not connect to port %d: %s' %
                      (bound_port, str(e)))
Beispiel #42
0
 def test_server (self):
     listener = socket.socket()
     listener.bind(('localhost', 0))
     listener.listen(50)
     serv = evy.spawn(backdoor.backdoor_server, listener)
     client = socket.socket()
     client.connect(('localhost', listener.getsockname()[1]))
     f = client.makefile('rw')
     self.assert_('Python' in f.readline())
     f.readline()  # build info
     f.readline()  # help info
     self.assert_('InteractiveConsole' in f.readline())
     self.assertEquals('>>> ', f.read(4))
     f.write('print("hi")\n')
     f.flush()
     self.assertEquals('hi\n', f.readline())
     self.assertEquals('>>> ', f.read(4))
     f.close()
     client.close()
     serv.kill()
     # wait for the console to discover that it's dead
     sleep(0.1)
Beispiel #43
0
    def test_timeout_and_final_write (self):
        """
        This test verifies that a write on a socket that we've stopped listening for doesn't
        result in an incorrect switch
        """
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        server.bind(('127.0.0.1', 0))
        server.listen(50)
        _, bound_port = server.getsockname()
        self.assertNotEqual(bound_port, 0)

        def sender (evt):
            s2, addr = server.accept()
            wrap_wfile = s2.makefile('w')

            sleep(0.02)
            wrap_wfile.write('hi')
            s2.close()
            evt.send('sent via event')

        from evy import event

        evt = event.Event()
        spawn(sender, evt)
        sleep(0)  # lets the socket enter accept mode, which
        # is necessary for connect to succeed on windows
        try:
            # try and get some data off of this pipe
            # but bail before any is sent
            Timeout(0.01)
            client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            client.connect(('127.0.0.1', bound_port))
            wrap_rfile = client.makefile()
            _c = wrap_rfile.read(1)
            self.fail()
        except socket.error, e:
            self.fail('could not connect to port %d: %s' % (bound_port, str(e)))
Beispiel #44
0
def connect(addr, family=socket.AF_INET, bind=None):
    """
    Convenience function for opening client sockets.

    :param addr: Address of the server to connect to.  For TCP sockets, this is a (host, port) tuple.
    :param family: Socket family, optional.  See :mod:`socket` documentation for available families.
    :param bind: Local address to bind to, optional.
    :return: The connected green socket object.
    """
    sock = socket.socket(family, socket.SOCK_STREAM)
    if bind is not None:
        sock.bind(bind)
    sock.connect(addr)
    return sock
Beispiel #45
0
def connect (addr, family = socket.AF_INET, bind = None):
    """
    Convenience function for opening client sockets.

    :param addr: Address of the server to connect to.  For TCP sockets, this is a (host, port) tuple.
    :param family: Socket family, optional.  See :mod:`socket` documentation for available families.
    :param bind: Local address to bind to, optional.
    :return: The connected green socket object.
    """
    sock = socket.socket(family, socket.SOCK_STREAM)
    if bind is not None:
        sock.bind(bind)
    sock.connect(addr)
    return sock
Beispiel #46
0
 def test_sock_name (self):
     # Testing getsockname()
     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.addCleanup(sock.close)
     sock.bind(("0.0.0.0", 0))
     name = sock.getsockname()
     # XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate
     # it reasonable to get the host's addr in addition to 0.0.0.0.
     # At least for eCos.  This is required for the S/390 to pass.
     try:
         my_ip_addr = socket.gethostbyname(socket.gethostname())
     except socket.error:
         # Probably name lookup wasn't set up right; skip this test
         return
     self.assertIn(name[0], ("0.0.0.0", my_ip_addr), '%s invalid' % name[0])
Beispiel #47
0
 def test_sock_name(self):
     # Testing getsockname()
     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.addCleanup(sock.close)
     sock.bind(("0.0.0.0", 0))
     name = sock.getsockname()
     # XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate
     # it reasonable to get the host's addr in addition to 0.0.0.0.
     # At least for eCos.  This is required for the S/390 to pass.
     try:
         my_ip_addr = socket.gethostbyname(socket.gethostname())
     except socket.error:
         # Probably name lookup wasn't set up right; skip this test
         return
     self.assertIn(name[0], ("0.0.0.0", my_ip_addr), '%s invalid' % name[0])
    def test_recvfrom_timeout (self):
        # Test recvfrom() timeout
        _timeout = 2
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock.settimeout(_timeout)
        # Prevent "Address already in use" socket exceptions
        test_support.bind_port(self.sock, self.localhost)

        _t1 = time.time()
        self.assertRaises(socket.error, self.sock.recvfrom, 8192)
        _t2 = time.time()

        _delta = abs(_t1 - _t2)
        self.assertTrue(_delta < _timeout + self.fuzz,
                        "timeout (%g) is %g seconds more than expected (%g)"
                        % (_delta, self.fuzz, _timeout))
Beispiel #49
0
    def test_recvfrom_timeout(self):
        # Test recvfrom() timeout
        _timeout = 2
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sock.settimeout(_timeout)
        # Prevent "Address already in use" socket exceptions
        test_support.bind_port(self.sock, self.localhost)

        _t1 = time.time()
        self.assertRaises(socket.error, self.sock.recvfrom, 8192)
        _t2 = time.time()

        _delta = abs(_t1 - _t2)
        self.assertTrue(
            _delta < _timeout + self.fuzz,
            "timeout (%g) is %g seconds more than expected (%g)" %
            (_delta, self.fuzz, _timeout))
Beispiel #50
0
def listen(addr, family=socket.AF_INET, backlog=50):
    """
    Convenience function for opening server sockets.  This
    socket can be used in :func:`~evy.serve` or a custom ``accept()`` loop.

    Sets SO_REUSEADDR on the socket to save on annoyance. 

    :param addr: Address to listen on.  For TCP sockets, this is a (host, port)  tuple.
    :param family: Socket family, optional.  See :mod:`socket` documentation for available families.
    :param backlog: The maximum number of queued connections. Should be at least 1; the maximum value is system-dependent.
    :return: The listening green socket object.
    """
    sock = socket.socket(family, socket.SOCK_STREAM)
    if sys.platform[:3] != "win":
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind(addr)
    sock.listen(backlog)
    return sock
Beispiel #51
0
def launch_green_threads ():
    from evy.patched import socket
    import evy

    def green_accepter (server_sock, pool):
        for i in xrange(CONCURRENCY):
            sock, addr = server_sock.accept()
            pool.spawn_n(reader, sock)

    pool = evy.GreenPool(CONCURRENCY * 2 + 1)
    server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_sock.bind(('localhost', 0))
    server_sock.listen(50)
    addr = ('localhost', server_sock.getsockname()[1])
    pool.spawn_n(green_accepter, server_sock, pool)
    for i in xrange(CONCURRENCY):
        pool.spawn_n(writer, addr, socket.socket)
    pool.waitall()
Beispiel #52
0
            def receiver():
                client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                client.connect(('127.0.0.1', listener_port))
                total = 0
                while total < many_bytes:
                    data = client.recv(
                        min(many_bytes - total, many_bytes // 10))
                    if not data:
                        break
                    total += len(data)

                total2 = 0
                while total < second_bytes:
                    data = client.recv(second_bytes)
                    if not data:
                        break
                    total2 += len(data)

                received.send()