Exemplo n.º 1
0
def test_task_context_relay_fork():
    endpoint1 = random_ipc_endpoint()
    endpoint2 = random_ipc_endpoint()
    srv_ctx = zerorpc.Context()
    srv_relay_ctx = zerorpc.Context()
    cli_ctx = zerorpc.Context()

    srv_tracer = Tracer("[server]")
    srv_ctx.register_middleware(srv_tracer)
    srv_relay_tracer = Tracer("[server_relay]")
    srv_relay_ctx.register_middleware(srv_relay_tracer)
    cli_tracer = Tracer("[client]")
    cli_ctx.register_middleware(cli_tracer)

    class Srv:
        def echo(self, msg):
            return msg

    srv = zerorpc.Server(Srv(), context=srv_ctx)
    srv.bind(endpoint1)
    srv_task = gevent.spawn(srv.run)

    c_relay = zerorpc.Client(context=srv_relay_ctx)
    c_relay.connect(endpoint1)

    class SrvRelay:
        def echo(self, msg):
            def dothework(msg):
                return c_relay.echo(msg) + "relayed"

            g = gevent.spawn(zerorpc.fork_task_context(dothework, srv_relay_ctx), "relay" + msg)
            print "relaying in separate task:", g
            r = g.get()
            print "back to main task"
            return r

    srv_relay = zerorpc.Server(SrvRelay(), context=srv_relay_ctx)
    srv_relay.bind(endpoint2)
    srv_relay_task = gevent.spawn(srv_relay.run)

    c = zerorpc.Client(context=cli_ctx)
    c.connect(endpoint2)

    assert c.echo("hello") == "relayhellorelayed"

    srv_relay.stop()
    srv.stop()
    srv_relay_task.join()
    srv_task.join()

    assert cli_tracer._log == [("new", cli_tracer.trace_id)]
    assert srv_relay_tracer._log == [
        ("load", cli_tracer.trace_id),
        ("reuse", cli_tracer.trace_id),
        ("load", cli_tracer.trace_id),
        ("reuse", cli_tracer.trace_id),
        ("reuse", cli_tracer.trace_id),
    ]
    assert srv_tracer._log == [("load", cli_tracer.trace_id), ("reuse", cli_tracer.trace_id)]
Exemplo n.º 2
0
def test_task_context_relay():
    endpoint1 = random_ipc_endpoint()
    endpoint2 = random_ipc_endpoint()
    srv_ctx = zerorpc.Context()
    srv_relay_ctx = zerorpc.Context()
    cli_ctx = zerorpc.Context()

    srv_tracer = Tracer('[server]')
    srv_ctx.register_middleware(srv_tracer)
    srv_relay_tracer = Tracer('[server_relay]')
    srv_relay_ctx.register_middleware(srv_relay_tracer)
    cli_tracer = Tracer('[client]')
    cli_ctx.register_middleware(cli_tracer)

    class Srv:
        def echo(self, msg):
            return msg

    srv = zerorpc.Server(Srv(), context=srv_ctx)
    srv.bind(endpoint1)
    srv_task = gevent.spawn(srv.run)

    c_relay = zerorpc.Client(context=srv_relay_ctx)
    c_relay.connect(endpoint1)

    class SrvRelay:
        def echo(self, msg):
            return c_relay.echo('relay' + msg) + 'relayed'

    srv_relay = zerorpc.Server(SrvRelay(), context=srv_relay_ctx)
    srv_relay.bind(endpoint2)
    srv_relay_task = gevent.spawn(srv_relay.run)

    c = zerorpc.Client(context=cli_ctx)
    c.connect(endpoint2)

    assert c.echo('hello') == 'relayhellorelayed'

    srv_relay.stop()
    srv.stop()
    srv_relay_task.join()
    srv_task.join()

    assert cli_tracer._log == [
            ('new', cli_tracer.trace_id),
            ]
    assert srv_relay_tracer._log == [
            ('load', cli_tracer.trace_id),
            ('reuse', cli_tracer.trace_id),
            ('reuse', cli_tracer.trace_id),
            ]
    assert srv_tracer._log == [
            ('load', cli_tracer.trace_id),
            ('reuse', cli_tracer.trace_id),
            ]
Exemplo n.º 3
0
def test_task_context_relay():
    endpoint1 = random_ipc_endpoint()
    endpoint2 = random_ipc_endpoint()
    srv_ctx = zerorpc.Context()
    srv_relay_ctx = zerorpc.Context()
    cli_ctx = zerorpc.Context()

    srv_tracer = Tracer('[server]')
    srv_ctx.register_middleware(srv_tracer)
    srv_relay_tracer = Tracer('[server_relay]')
    srv_relay_ctx.register_middleware(srv_relay_tracer)
    cli_tracer = Tracer('[client]')
    cli_ctx.register_middleware(cli_tracer)

    class Srv:
        def echo(self, msg):
            return msg

    srv = zerorpc.Server(Srv(), context=srv_ctx)
    srv.bind(endpoint1)
    srv_task = gevent.spawn(srv.run)

    c_relay = zerorpc.Client(context=srv_relay_ctx)
    c_relay.connect(endpoint1)

    class SrvRelay:
        def echo(self, msg):
            return c_relay.echo('relay' + msg) + 'relayed'

    srv_relay = zerorpc.Server(SrvRelay(), context=srv_relay_ctx)
    srv_relay.bind(endpoint2)
    srv_relay_task = gevent.spawn(srv_relay.run)

    c = zerorpc.Client(context=cli_ctx)
    c.connect(endpoint2)

    assert c.echo('hello') == 'relayhellorelayed'

    srv_relay.stop()
    srv.stop()
    srv_relay_task.join()
    srv_task.join()

    assert cli_tracer._log == [
        ('new', cli_tracer.trace_id),
    ]
    assert srv_relay_tracer._log == [
        ('load', cli_tracer.trace_id),
        ('reuse', cli_tracer.trace_id),
        ('reuse', cli_tracer.trace_id),
    ]
    assert srv_tracer._log == [
        ('load', cli_tracer.trace_id),
        ('reuse', cli_tracer.trace_id),
    ]
Exemplo n.º 4
0
def test_config_multiple_endpoints():
    app = Zask(__name__)
    endpoint = random_ipc_endpoint()
    another_endpoint = random_ipc_endpoint()

    app.config['ZERORPC_SOME_SERVICE'] = {
        '1.0': endpoint,
    }
    app.config['ZERORPC_SOME_SERVICE_2'] = {
        '1.0': another_endpoint
    }
    app.config['ZERORPC_SOME_SERVICE_CLIENT'] = {
        '1.0': [
            endpoint,
            another_endpoint
        ],
        'default': '1.0'
    }
    rpc = ZeroRPC(app, middlewares=[CONFIG_ENDPOINT_MIDDLEWARE])

    class Srv(object):
        __version__ = "1.0"
        __service_name__ = "some_service"

        def hello(self):
            return 'i am server 1'

    class AnotherSrv(object):
        __version__ = "1.0"
        __service_name__ = "some_service_2"

        def hello(self):
            return 'i am server 2'

    srv = rpc.Server(Srv())
    another_srv = rpc.Server(AnotherSrv())
    gevent.spawn(srv.run)
    gevent.spawn(another_srv.run)

    client = rpc.Client('some_service_client')
    for i in range(5):
        who_i_am = client.hello()
        app.logger.debug(who_i_am)
        assert who_i_am == 'i am server 1' or who_i_am == 'i am server 2'

    with pytest.raises(MissingConfigException):
        client = rpc.Client('some_service_client', version='2.0')

    client.close()
    srv.close()
    another_srv.close()
Exemplo n.º 5
0
def test_config_multiple_endpoints():
    app = Zask(__name__)
    endpoint = random_ipc_endpoint()
    another_endpoint = random_ipc_endpoint()

    app.config['ZERORPC_SOME_SERVICE'] = {
        '1.0': endpoint,
    }
    app.config['ZERORPC_SOME_SERVICE_2'] = {
        '1.0': another_endpoint
    }
    app.config['ZERORPC_SOME_SERVICE_CLIENT'] = {
        '1.0': [
            endpoint,
            another_endpoint
        ],
        'default': '1.0'
    }
    rpc = ZeroRPC(app, middlewares=[CONFIG_ENDPOINT_MIDDLEWARE])

    class Srv(object):
        __version__ = "1.0"
        __service_name__ = "some_service"

        def hello(self):
            return 'i am server 1'

    class AnotherSrv(object):
        __version__ = "1.0"
        __service_name__ = "some_service_2"

        def hello(self):
            return 'i am server 2'

    srv = rpc.Server(Srv())
    another_srv = rpc.Server(AnotherSrv())
    gevent.spawn(srv.run)
    gevent.spawn(another_srv.run)

    client = rpc.Client('some_service_client')
    for i in range(5):
        who_i_am = client.hello()
        app.logger.debug(who_i_am)
        assert who_i_am == 'i am server 1' or who_i_am == 'i am server 2'

    with pytest.raises(MissingConfigException):
        client = rpc.Client('some_service_client', version='2.0')

    client.close()
    srv.close()
    another_srv.close()
Exemplo n.º 6
0
def test_client_server_detailed_exception():
    endpoint = random_ipc_endpoint()

    class MySrv(zerorpc.Server):

        def raise_error(self):
            raise RuntimeError('oops!')

    srv = MySrv()
    srv.bind(endpoint)
    gevent.spawn(srv.run)

    client = zerorpc.Client(timeout=2)
    client.connect(endpoint)

    with assert_raises(zerorpc.RemoteError):
        print client.raise_error()
    try:
        client.raise_error()
    except zerorpc.RemoteError as e:
        print 'got that:', e
        print 'name', e.name
        print 'msg', e.msg
        assert e.name == 'RuntimeError'
        assert e.msg == 'oops!'

    client.close()
    srv.close()
Exemplo n.º 7
0
def test_server_manual():
    endpoint = random_ipc_endpoint()

    class MySrv(zerorpc.Server):

        def lolita(self):
            return 42

        def add(self, a, b):
            return a + b

    srv = MySrv()
    srv.bind(endpoint)
    gevent.spawn(srv.run)

    client_events = zerorpc.Events(zmq.XREQ)
    client_events.connect(endpoint)
    client = zerorpc.ChannelMultiplexer(client_events, ignore_broadcast=True)

    client_channel = client.channel()
    client_channel.emit('lolita', tuple())
    event = client_channel.recv()
    assert event.args == (42,)
    client_channel.close()

    client_channel = client.channel()
    client_channel.emit('add', (1, 2))
    event = client_channel.recv()
    assert event.args == (3,)
    client_channel.close()
    srv.stop()
def test_heartbeat_can_open_channel_server_close():
    endpoint = random_ipc_endpoint()
    server_events = zerorpc.Events(zmq.XREP)
    server_events.bind(endpoint)
    server = zerorpc.ChannelMultiplexer(server_events)

    client_events = zerorpc.Events(zmq.XREQ)
    client_events.connect(endpoint)
    client = zerorpc.ChannelMultiplexer(client_events, ignore_broadcast=True)

    client_channel = client.channel()
    client_hbchan = zerorpc.HeartBeatOnChannel(client_channel, freq=1)
    client_bufchan = zerorpc.BufferedChannel(client_hbchan)

    event = server.recv()
    server_channel = server.channel(event)
    server_hbchan = zerorpc.HeartBeatOnChannel(server_channel, freq=1)
    server_bufchan = zerorpc.BufferedChannel(server_hbchan)

    gevent.sleep(3)
    print "CLOSE SERVER SOCKET!!!"
    server_bufchan.close()
    with assert_raises(zerorpc.LostRemote):
        client_bufchan.recv()
    print "CLIENT LOST SERVER :)"
    client_bufchan.close()
    server.close()
    client.close()
Exemplo n.º 9
0
def test_events_channel_both_side():
    endpoint = random_ipc_endpoint()
    server_events = zerorpc.Events(zmq.XREP)
    server_events.bind(endpoint)
    server = zerorpc.ChannelMultiplexer(server_events)

    client_events = zerorpc.Events(zmq.XREQ)
    client_events.connect(endpoint)
    client = zerorpc.ChannelMultiplexer(client_events)

    client_channel = client.channel()
    client_channel.emit("openthat", (42,))

    event = server.recv()
    print event
    assert event.args == (42,)
    assert event.name == "openthat"

    server_channel = server.channel(event)
    server_channel.emit("test", (21,))

    event = client_channel.recv()
    assert event.args == (21,)
    assert event.name == "test"

    server_channel.emit("test", (22,))

    event = client_channel.recv()
    assert event.args == (22,)
    assert event.name == "test"

    server_events.close()
    server_channel.close()
    client_channel.close()
    client_events.close()
def test_close_client_bufchan():
    endpoint = random_ipc_endpoint()
    server_events = zerorpc.Events(zmq.XREP)
    server_events.bind(endpoint)
    server = zerorpc.ChannelMultiplexer(server_events)

    client_events = zerorpc.Events(zmq.XREQ)
    client_events.connect(endpoint)
    client = zerorpc.ChannelMultiplexer(client_events, ignore_broadcast=True)

    client_channel = client.channel()
    client_hbchan = zerorpc.HeartBeatOnChannel(client_channel, freq=1)
    client_bufchan = zerorpc.BufferedChannel(client_hbchan)
    client_bufchan.emit('openthat', None)

    event = server.recv()
    server_channel = server.channel(event)
    server_hbchan = zerorpc.HeartBeatOnChannel(server_channel, freq=1)
    server_bufchan = zerorpc.BufferedChannel(server_hbchan)
    server_bufchan.recv()

    gevent.sleep(3)
    print 'CLOSE CLIENT SOCKET!!!'
    client_bufchan.close()
    with assert_raises(zerorpc.LostRemote):
        server_bufchan.recv()
    print 'SERVER LOST CLIENT :)'
    server_bufchan.close()
    server.close()
    client.close()
Exemplo n.º 11
0
def test1():
    endpoint = random_ipc_endpoint()
    def server():
        c = zmq.Context()
        s = c.socket(zmq.REP)
        s.bind(endpoint)
        while True:
            print 'srv recving...'
            r = s.recv()
            print 'srv', r
            print 'srv sending...'
            s.send('world')

        s.close()
        c.term()

    def client():
        c = zmq.Context()
        s = c.socket(zmq.REQ)
        s.connect(endpoint)

        print 'cli sending...'
        s.send('hello')
        print 'cli recving...'
        r = s.recv()
        print 'cli', r

        s.close()
        c.term()

    s = gevent.spawn(server)
    c = gevent.spawn(client)
    c.join()
Exemplo n.º 12
0
def test_events_channel_both_side():
    endpoint = random_ipc_endpoint()
    server_events = zerorpc.Events(zmq.ROUTER)
    server_events.bind(endpoint)
    server = zerorpc.ChannelMultiplexer(server_events)

    client_events = zerorpc.Events(zmq.DEALER)
    client_events.connect(endpoint)
    client = zerorpc.ChannelMultiplexer(client_events)

    client_channel = client.channel()
    client_channel.emit('openthat', (42,))

    event = server.recv()
    print event
    assert list(event.args) == [42]
    assert event.name == 'openthat'

    server_channel = server.channel(event)
    server_channel.emit('test', (21,))

    event = client_channel.recv()
    assert list(event.args) == [21]
    assert event.name == 'test'

    server_channel.emit('test', (22,))

    event = client_channel.recv()
    assert list(event.args) == [22]
    assert event.name == 'test'

    server_events.close()
    server_channel.close()
    client_channel.close()
    client_events.close()
def test_hook_client_handle_remote_error_inspect():

    class ClientHandleRemoteErrorMiddleware(object):
        def __init__(self):
            self.called = False
        def client_handle_remote_error(self, event):
            self.called = True

    test_middleware = ClientHandleRemoteErrorMiddleware()
    zero_ctx = zerorpc.Context()
    zero_ctx.register_middleware(test_middleware)
    endpoint = random_ipc_endpoint()

    test_server = zerorpc.Server(EchoModule(), context=zero_ctx)
    test_server.bind(endpoint)
    test_server_task = gevent.spawn(test_server.run)

    test_client = zerorpc.Client(context=zero_ctx)
    test_client.connect(endpoint)

    assert test_middleware.called == False
    try:
        test_client.crash("test")
    except zerorpc.RemoteError as ex:
        assert test_middleware.called == True
        assert ex.name == "RuntimeError"

    test_server.stop()
    test_server_task.join()
Exemplo n.º 14
0
def test_close_client_hbchan():
    endpoint = random_ipc_endpoint()
    server_events = zerorpc.Events(zmq.ROUTER)
    server_events.bind(endpoint)
    server = zerorpc.ChannelMultiplexer(server_events)

    client_events = zerorpc.Events(zmq.DEALER)
    client_events.connect(endpoint)
    client = zerorpc.ChannelMultiplexer(client_events, ignore_broadcast=True)

    client_channel = client.channel()
    client_hbchan = zerorpc.HeartBeatOnChannel(client_channel,
                                               freq=TIME_FACTOR * 2)
    client_hbchan.emit('openthat', None)

    event = server.recv()
    server_channel = server.channel(event)
    server_hbchan = zerorpc.HeartBeatOnChannel(server_channel,
                                               freq=TIME_FACTOR * 2)
    server_hbchan.recv()

    gevent.sleep(TIME_FACTOR * 3)
    print 'CLOSE CLIENT SOCKET!!!'
    client_hbchan.close()
    if sys.version_info < (2, 7):
        assert_raises(zerorpc.LostRemote, server_hbchan.recv)
    else:
        with assert_raises(zerorpc.LostRemote):
            server_hbchan.recv()
    print 'SERVER LOST CLIENT :)'
    server_hbchan.close()
    server.close()
    client.close()
Exemplo n.º 15
0
def test_events_channel_client_side_server_send_many():
    endpoint = random_ipc_endpoint()
    server_events = zerorpc.Events(zmq.ROUTER)
    server_events.bind(endpoint)
    server = zerorpc.ChannelMultiplexer(server_events)

    client_events = zerorpc.Events(zmq.DEALER)
    client_events.connect(endpoint)
    client = zerorpc.ChannelMultiplexer(client_events)

    client_channel = client.channel()
    client_channel.emit('giveme', (10,))

    event = server.recv()
    print event
    assert list(event.args) == [10]
    assert event.header.get('zmqid', None) is not None

    for x in xrange(10):
        server.emit('someanswer', (x,),
                xheader=dict(response_to=event.header['message_id'],
                    zmqid=event.header['zmqid']))
    for x in xrange(10):
        event = client_channel.recv()
        assert list(event.args) == [x]
Exemplo n.º 16
0
def test_client_server_client_timeout():
    endpoint = random_ipc_endpoint()

    class MySrv(zerorpc.Server):
        def lolita(self):
            return 42

        def add(self, a, b):
            gevent.sleep(TIME_FACTOR * 10)
            return a + b

    srv = MySrv()
    srv.bind(endpoint)
    gevent.spawn(srv.run)

    client = zerorpc.Client(timeout=TIME_FACTOR * 2)
    client.connect(endpoint)

    if sys.version_info < (2, 7):
        assert_raises(zerorpc.TimeoutExpired, client.add, 1, 4)
    else:
        with assert_raises(zerorpc.TimeoutExpired):
            print client.add(1, 4)
    client.close()
    srv.close()
Exemplo n.º 17
0
def test_client_server_exception():
    endpoint = random_ipc_endpoint()

    class MySrv(zerorpc.Server):
        def raise_something(self, a):
            return a[4]

    srv = MySrv()
    srv.bind(endpoint)
    gevent.spawn(srv.run)

    client = zerorpc.Client(timeout=TIME_FACTOR * 2)
    client.connect(endpoint)

    if sys.version_info < (2, 7):

        def _do_with_assert_raises():
            print client.raise_something(42)

        assert_raises(zerorpc.RemoteError, _do_with_assert_raises)
    else:
        with assert_raises(zerorpc.RemoteError):
            print client.raise_something(42)
    assert client.raise_something(range(5)) == 4
    client.close()
    srv.close()
Exemplo n.º 18
0
def test_pubsub_inheritance():
    endpoint = random_ipc_endpoint()

    publisher = zerorpc.Publisher()
    publisher.bind(endpoint)
    trigger = gevent.event.Event()

    class Subscriber(zerorpc.Subscriber):
        def lolita(self, a, b):
            print "lolita", a, b
            assert a + b == 3
            trigger.set()

    subscriber = Subscriber()
    subscriber.connect(endpoint)
    gevent.spawn(subscriber.run)

    trigger.clear()
    # We need this retry logic to wait that the subscriber.run coroutine starts
    # reading (the published messages will go to /dev/null until then).
    for attempt in xrange(0, 10):
        publisher.lolita(1, 2)
        if trigger.wait(0.2):
            print "done"
            return

    raise RuntimeError("The subscriber didn't receive any published message")
Exemplo n.º 19
0
def test_events_channel_client_side_server_send_many():
    endpoint = random_ipc_endpoint()

    server_events = zerorpc.Events(zmq.ROUTER)
    server_events.bind(endpoint)
    server = zerorpc.ChannelMultiplexer(server_events)

    client_events = zerorpc.Events(zmq.DEALER)
    client_events.connect(endpoint)
    client = zerorpc.ChannelMultiplexer(client_events)

    client_channel = client.channel()
    client_channel.emit('giveme', (10, ))

    # 客户端发送Event, Server接受event, 并且验证
    event = server.recv()
    print event
    assert list(event.args) == [10]

    assert event.header.get('zmqid', None) is not None

    # 服务器批量发送消息,客户端批量接受信息
    print "message_id: ", event.header['message_id']
    print "zmqid: ", event.header['zmqid']

    for x in xrange(10):
        server.emit('someanswer', (x, ),
                    xheader=dict(response_to=event.header['message_id'],
                                 zmqid=event.header['zmqid']))

    for x in xrange(10):
        event = client_channel.recv()
        assert list(event.args) == [x]
Exemplo n.º 20
0
def test_close_client_hbchan():
    endpoint = random_ipc_endpoint()
    server_events = zerorpc.Events(zmq.ROUTER)
    server_events.bind(endpoint)
    server = zerorpc.ChannelMultiplexer(server_events)

    client_events = zerorpc.Events(zmq.DEALER)
    client_events.connect(endpoint)
    client = zerorpc.ChannelMultiplexer(client_events, ignore_broadcast=True)

    client_channel = client.channel()
    client_hbchan = zerorpc.HeartBeatOnChannel(client_channel, freq=2)
    client_hbchan.emit('openthat', None)

    event = server.recv()
    server_channel = server.channel(event)
    server_hbchan = zerorpc.HeartBeatOnChannel(server_channel, freq=2)
    server_hbchan.recv()

    gevent.sleep(3)
    print 'CLOSE CLIENT SOCKET!!!'
    client_hbchan.close()
    if sys.version_info < (2, 7):
        assert_raises(zerorpc.LostRemote, server_hbchan.recv)
    else:
        with assert_raises(zerorpc.LostRemote):
            server_hbchan.recv()
    print 'SERVER LOST CLIENT :)'
    server_hbchan.close()
    server.close()
    client.close()
def test_hook_client_after_request_stream():
    zero_ctx = zerorpc.Context()
    endpoint = random_ipc_endpoint()

    test_server = zerorpc.Server(EchoModule(), context=zero_ctx)
    test_server.bind(endpoint)
    test_server_task = gevent.spawn(test_server.run)

    test_client = zerorpc.Client(context=zero_ctx)
    test_client.connect(endpoint)

    it = test_client.echoes("test")
    assert next(it) == "echo: test"
    for echo in it:
        assert echo == "echo: test"

    test_middleware = ClientAfterRequestMiddleware()
    zero_ctx.register_middleware(test_middleware)
    assert test_middleware.called == False
    it = test_client.echoes("test")
    assert next(it) == "echo: test"
    assert test_middleware.called == False
    for echo in it:
        assert echo == "echo: test"
    assert test_middleware.called == True
    assert test_middleware.retcode == 'STREAM_DONE'

    test_server.stop()
    test_server_task.join()
Exemplo n.º 22
0
def test_rcp_streaming():
    endpoint = random_ipc_endpoint()

    class MySrv(zerorpc.Server):

        @zerorpc.rep
        def range(self, max):
            return xrange(max)

        @zerorpc.stream
        def xrange(self, max):
            return xrange(max)

    srv = MySrv(heartbeat=2)
    srv.bind(endpoint)
    gevent.spawn(srv.run)

    client = zerorpc.Client(heartbeat=2)
    client.connect(endpoint)

    r = client.range(10)
    assert r == tuple(range(10))

    r = client.xrange(10)
    assert getattr(r, 'next', None) is not None
    l = []
    print 'wait 4s for fun'
    gevent.sleep(4)
    for x in r:
        l.append(x)
    assert l == range(10)
Exemplo n.º 23
0
def test1():
    endpoint = random_ipc_endpoint()

    def server():
        c = zmq.Context()
        s = c.socket(zmq.REP)
        s.bind(endpoint)
        while True:
            print 'srv recving...'
            r = s.recv()
            print 'srv', r
            print 'srv sending...'
            s.send('world')

        s.close()
        c.term()

    def client():
        c = zmq.Context()
        s = c.socket(zmq.REQ)
        s.connect(endpoint)

        print 'cli sending...'
        s.send('hello')
        print 'cli recving...'
        r = s.recv()
        print 'cli', r

        s.close()
        c.term()

    s = gevent.spawn(server)
    c = gevent.spawn(client)
    c.join()
Exemplo n.º 24
0
def test_config_endpoint_1():
    app = Zask(__name__)
    endpoint = random_ipc_endpoint()
    app.config['ZERORPC_SOME_SERVICE'] = {
        '1.0': endpoint,
    }
    rpc = ZeroRPC(app, middlewares=[CONFIG_ENDPOINT_MIDDLEWARE])

    class Srv(rpc.Server):
        __version__ = "1.0"
        __service_name__ = "some_service"

        def hello(self):
            return 'world'

    srv = Srv()
    gevent.spawn(srv.run)

    client = rpc.Client('some_service', version='1.0')
    assert client.hello() == 'world'

    with pytest.raises(ClientMissingVersionException):
        client = rpc.Client('some_service')

    client.close()
    srv.close()
Exemplo n.º 25
0
def test_events_channel_client_side():
    endpoint = random_ipc_endpoint()
    server_events = zerorpc.Events(zmq.ROUTER)
    server_events.bind(endpoint)
    server = zerorpc.ChannelMultiplexer(server_events)

    client_events = zerorpc.Events(zmq.DEALER)
    client_events.connect(endpoint)
    client = zerorpc.ChannelMultiplexer(client_events)

    client_channel = client.channel()
    client_channel.emit('someevent', (42, ))

    event = server.recv()
    print event
    assert list(event.args) == [42]
    assert event.identity is not None

    reply_event = server.new_event(
        'someanswer', (21, ),
        xheader=dict(response_to=event.header['message_id']))
    reply_event.identity = event.identity
    server.emit_event(reply_event)
    event = client_channel.recv()
    assert list(event.args) == [21]
Exemplo n.º 26
0
def test_pubsub_inheritance():
    endpoint = random_ipc_endpoint()

    publisher = zerorpc.Publisher()
    publisher.bind(endpoint)
    trigger = gevent.event.Event()

    class Subscriber(zerorpc.Subscriber):
        def lolita(self, a, b):
            print 'lolita', a, b
            assert a + b == 3
            trigger.set()

    subscriber = Subscriber()
    subscriber.connect(endpoint)
    gevent.spawn(subscriber.run)

    trigger.clear()
    # We need this retry logic to wait that the subscriber.run coroutine starts
    # reading (the published messages will go to /dev/null until then).
    for attempt in xrange(0, 10):
        publisher.lolita(1, 2)
        if trigger.wait(0.2):
            print 'done'
            return

    raise RuntimeError("The subscriber didn't receive any published message")
Exemplo n.º 27
0
def test_exception_compat_v1():
    endpoint = random_ipc_endpoint()

    class MySrv(zerorpc.Server):
        pass

    srv = MySrv()
    srv.bind(endpoint)
    gevent.spawn(srv.run)

    client_events = zerorpc.Events(zmq.XREQ)
    client_events.connect(endpoint)
    client = zerorpc.ChannelMultiplexer(client_events, ignore_broadcast=True)

    rpccall = client.channel()
    rpccall.emit('donotexist', tuple())
    event = rpccall.recv()
    print event
    assert event.name == 'ERR'
    (name, msg, tb) = event.args
    print 'detailed error', name, msg, tb
    assert name == 'NameError'
    assert msg == 'donotexist'

    rpccall = client.channel()
    rpccall.emit('donotexist', tuple(), xheader=dict(v=1))
    event = rpccall.recv()
    print event
    assert event.name == 'ERR'
    (msg, ) = event.args
    print 'msg only', msg
    assert msg == "NameError('donotexist',)"

    client_events.close()
    srv.close()
def test_hook_server_after_exec_stream():
    zero_ctx = zerorpc.Context()
    endpoint = random_ipc_endpoint()

    test_server = zerorpc.Server(EchoModule(), context=zero_ctx)
    test_server.bind(endpoint)
    test_server_task = gevent.spawn(test_server.run)
    test_client = zerorpc.Client()
    test_client.connect(endpoint)

    # Test without a middleware
    for echo in test_client.echoes("test"):
        assert echo == "echo: test"

    # Test with a middleware
    test_middleware = ServerAfterExecMiddleware()
    zero_ctx.register_middleware(test_middleware)
    assert test_middleware.called == False
    it = test_client.echoes("test")
    assert next(it) == "echo: test"
    assert test_middleware.called == False
    for echo in it:
        assert echo == "echo: test"
    assert test_middleware.called == True
    assert test_middleware.request_event_name == 'echoes'
    assert test_middleware.reply_event_name == 'STREAM_DONE'

    test_server.stop()
    test_server_task.join()
Exemplo n.º 29
0
def test_events_channel_client_side_server_send_many():
    endpoint = random_ipc_endpoint()
    server_events = zerorpc.Events(zmq.XREP)
    server_events.bind(endpoint)
    server = zerorpc.ChannelMultiplexer(server_events)

    client_events = zerorpc.Events(zmq.XREQ)
    client_events.connect(endpoint)
    client = zerorpc.ChannelMultiplexer(client_events)

    client_channel = client.channel()
    client_channel.emit('giveme', (10,))

    event = server.recv()
    print event
    assert event.args == (10,)
    assert event.header.get('zmqid', None) is not None

    for x in xrange(10):
        server.emit('someanswer', (x,),
                xheader=dict(response_to=event.header['message_id'],
                    zmqid=event.header['zmqid']))
    for x in xrange(10):
        event = client_channel.recv()
        assert event.args == (x,)
def test_hook_server_after_exec_on_error_puller():
    zero_ctx = zerorpc.Context()
    trigger = gevent.event.Event()
    endpoint = random_ipc_endpoint()

    echo_module = BrokenEchoModule(trigger)
    test_server = zerorpc.Puller(echo_module, context=zero_ctx)
    test_server.bind(endpoint)
    test_server_task = gevent.spawn(test_server.run)
    test_client = zerorpc.Pusher()
    test_client.connect(endpoint)

    test_middleware = ServerAfterExecMiddleware()
    zero_ctx.register_middleware(test_middleware)
    assert test_middleware.called == False
    try:
        test_client.echo("test with a middleware")
        trigger.wait(timeout=TIME_FACTOR * 2)
    except zerorpc.RemoteError:
        pass
    assert echo_module.last_msg == "Raise"
    assert test_middleware.called == False

    test_server.stop()
    test_server_task.join()
Exemplo n.º 31
0
def testing_scope_session():
    app = Zask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
    app.config['DEBUG'] = False
    db = sqlalchemy.SQLAlchemy(app)

    endpoint = random_ipc_endpoint()
    rpc = ZeroRPC(app, middlewares=None)
    rpc.register_middleware(sqlalchemy.SessionMiddleware(db))

    class Foo(object):
        def create_foo(self, ctx):
            ctx2 = _request_ctx.get_request_cxt()
            assert ctx == ctx2

    class Srv(rpc.Server):
        def get_session(self):
            ctx = _request_ctx.get_request_cxt()
            foo = Foo()
            foo.create_foo(ctx)

            return str(db.session())

    srv = Srv(pool_size=1)
    srv.bind(endpoint)
    gevent.spawn(srv.run)

    client = rpc.Client(endpoint)
    session1 = client.get_session(async=True)
    session2 = client.get_session(async=True)

    assert session1.get() != session2.get()
def test_hook_server_before_exec_puller():
    zero_ctx = zerorpc.Context()
    trigger = gevent.event.Event()
    endpoint = random_ipc_endpoint()

    echo_module = EchoModule(trigger)
    test_server = zerorpc.Puller(echo_module, context=zero_ctx)
    test_server.bind(endpoint)
    test_server_task = gevent.spawn(test_server.run)
    test_client = zerorpc.Pusher()
    test_client.connect(endpoint)

    # Test without a middleware
    test_client.echo("test")
    trigger.wait(timeout=TIME_FACTOR * 2)
    assert echo_module.last_msg == "echo: test"
    trigger.clear()

    # Test with a middleware
    test_middleware = ServerBeforeExecMiddleware()
    zero_ctx.register_middleware(test_middleware)
    assert test_middleware.called == False
    test_client.echo("test with a middleware")
    trigger.wait(timeout=TIME_FACTOR * 2)
    assert echo_module.last_msg == "echo: test with a middleware"
    assert test_middleware.called == True

    test_server.stop()
    test_server_task.join()
Exemplo n.º 33
0
def test_events_channel_client_side_server_send_many():
    endpoint = random_ipc_endpoint()
    server_events = zerorpc.Events(zmq.XREP)
    server_events.bind(endpoint)
    server = zerorpc.ChannelMultiplexer(server_events)

    client_events = zerorpc.Events(zmq.XREQ)
    client_events.connect(endpoint)
    client = zerorpc.ChannelMultiplexer(client_events)

    client_channel = client.channel()
    client_channel.emit("giveme", (10,))

    event = server.recv()
    print event
    assert event.args == (10,)
    assert event.header.get("zmqid", None) is not None

    for x in xrange(10):
        server.emit(
            "someanswer", (x,), xheader=dict(response_to=event.header["message_id"], zmqid=event.header["zmqid"])
        )
    for x in xrange(10):
        event = client_channel.recv()
        assert event.args == (x,)
def test_hook_client_after_request_stream():
    zero_ctx = zerorpc.Context()
    endpoint = random_ipc_endpoint()

    test_server = zerorpc.Server(EchoModule(), context=zero_ctx)
    test_server.bind(endpoint)
    test_server_task = gevent.spawn(test_server.run)

    test_client = zerorpc.Client(context=zero_ctx)
    test_client.connect(endpoint)

    it = test_client.echoes("test")
    assert next(it) == "echo: test"
    for echo in it:
        assert echo == "echo: test"

    test_middleware = ClientAfterRequestMiddleware()
    zero_ctx.register_middleware(test_middleware)
    assert test_middleware.called == False
    it = test_client.echoes("test")
    assert next(it) == "echo: test"
    assert test_middleware.called == False
    for echo in it:
        assert echo == "echo: test"
    assert test_middleware.called == True
    assert test_middleware.retcode == 'STREAM_DONE'

    test_server.stop()
    test_server_task.join()
def test_heartbeat_can_open_channel_server_close():
    endpoint = random_ipc_endpoint()
    server_events = zerorpc.Events(zmq.ROUTER)
    server_events.bind(endpoint)
    server = zerorpc.ChannelMultiplexer(server_events)

    client_events = zerorpc.Events(zmq.DEALER)
    client_events.connect(endpoint)
    client = zerorpc.ChannelMultiplexer(client_events, ignore_broadcast=True)

    client_channel = client.channel()
    client_hbchan = zerorpc.HeartBeatOnChannel(client_channel, freq=TIME_FACTOR * 2)
    client_bufchan = zerorpc.BufferedChannel(client_hbchan)

    event = server.recv()
    server_channel = server.channel(event)
    server_hbchan = zerorpc.HeartBeatOnChannel(server_channel, freq=TIME_FACTOR * 2)
    server_bufchan = zerorpc.BufferedChannel(server_hbchan)

    gevent.sleep(TIME_FACTOR * 3)
    print 'CLOSE SERVER SOCKET!!!'
    server_bufchan.close()
    if sys.version_info < (2, 7):
        assert_raises(zerorpc.LostRemote, client_bufchan.recv)
    else:
        with assert_raises(zerorpc.LostRemote):
            client_bufchan.recv()
    print 'CLIENT LOST SERVER :)'
    client_bufchan.close()
    server.close()
    client.close()
def test_hook_client_after_request_timeout():
    class ClientAfterRequestMiddleware(object):
        def __init__(self):
            self.called = False

        def client_after_request(self, req_event, rep_event, exception):
            self.called = True
            assert req_event is not None
            assert req_event.name == "timeout"
            assert rep_event is None

    zero_ctx = zerorpc.Context()
    test_middleware = ClientAfterRequestMiddleware()
    zero_ctx.register_middleware(test_middleware)
    endpoint = random_ipc_endpoint()

    test_server = zerorpc.Server(EchoModule(), context=zero_ctx)
    test_server.bind(endpoint)
    test_server_task = gevent.spawn(test_server.run)

    test_client = zerorpc.Client(timeout=TIME_FACTOR * 1, context=zero_ctx)
    test_client.connect(endpoint)

    assert test_middleware.called == False
    try:
        test_client.timeout("test")
    except zerorpc.TimeoutExpired as ex:
        assert test_middleware.called == True
        assert "timeout" in ex.args[0]

    test_server.stop()
    test_server_task.join()
Exemplo n.º 37
0
def test_exception_compat_v1():
    endpoint = random_ipc_endpoint()

    class MySrv(zerorpc.Server):
        pass

    srv = MySrv()
    srv.bind(endpoint)
    gevent.spawn(srv.run)

    client_events = zerorpc.Events(zmq.XREQ)
    client_events.connect(endpoint)
    client = zerorpc.ChannelMultiplexer(client_events, ignore_broadcast=True)

    rpccall = client.channel()
    rpccall.emit('donotexist', tuple())
    event = rpccall.recv()
    print event
    assert event.name == 'ERR'
    (name, msg, tb) = event.args
    print 'detailed error', name, msg, tb
    assert name == 'NameError'
    assert msg == 'donotexist'

    rpccall = client.channel()
    rpccall.emit('donotexist', tuple(), xheader=dict(v=1))
    event = rpccall.recv()
    print event
    assert event.name == 'ERR'
    (msg,) = event.args
    print 'msg only', msg
    assert msg == "NameError('donotexist',)"

    client_events.close()
    srv.close()
def test_hook_client_handle_remote_error_inspect():
    class ClientHandleRemoteErrorMiddleware(object):
        def __init__(self):
            self.called = False

        def client_handle_remote_error(self, event):
            self.called = True

    test_middleware = ClientHandleRemoteErrorMiddleware()
    zero_ctx = zerorpc.Context()
    zero_ctx.register_middleware(test_middleware)
    endpoint = random_ipc_endpoint()

    test_server = zerorpc.Server(EchoModule(), context=zero_ctx)
    test_server.bind(endpoint)
    test_server_task = gevent.spawn(test_server.run)

    test_client = zerorpc.Client(context=zero_ctx)
    test_client.connect(endpoint)

    assert test_middleware.called == False
    try:
        test_client.crash("test")
    except zerorpc.RemoteError as ex:
        assert test_middleware.called == True
        assert ex.name == "RuntimeError"

    test_server.stop()
    test_server_task.join()
Exemplo n.º 39
0
def test_rcp_streaming():
    endpoint = random_ipc_endpoint()

    class MySrv(zerorpc.Server):

        @zerorpc.rep
        def range(self, max):
            return range(max)

        @zerorpc.stream
        def xrange(self, max):
            return xrange(max)

    srv = MySrv(heartbeat=TIME_FACTOR * 4)
    srv.bind(endpoint)
    gevent.spawn(srv.run)

    client = zerorpc.Client(heartbeat=TIME_FACTOR * 4)
    client.connect(endpoint)

    r = client.range(10)
    assert list(r) == list(range(10))

    r = client.xrange(10)
    assert getattr(r, 'next', None) is not None
    l = []
    print 'wait 4s for fun'
    gevent.sleep(TIME_FACTOR * 4)
    for x in r:
        l.append(x)
    assert l == range(10)
def test_hook_client_before_request():
    class ClientBeforeRequestMiddleware(object):
        def __init__(self):
            self.called = False

        def client_before_request(self, event):
            self.called = True
            self.method = event.name

    zero_ctx = zerorpc.Context()
    endpoint = random_ipc_endpoint()

    test_server = zerorpc.Server(EchoModule(), context=zero_ctx)
    test_server.bind(endpoint)
    test_server_task = gevent.spawn(test_server.run)

    test_client = zerorpc.Client(context=zero_ctx)
    test_client.connect(endpoint)

    assert test_client.echo("test") == "echo: test"

    test_middleware = ClientBeforeRequestMiddleware()
    zero_ctx.register_middleware(test_middleware)
    assert test_middleware.called == False
    assert test_client.echo("test") == "echo: test"
    assert test_middleware.called == True
    assert test_middleware.method == 'echo'

    test_server.stop()
    test_server_task.join()
Exemplo n.º 41
0
def test_resolve_endpoint_events():
    test_endpoint = random_ipc_endpoint()
    c = zerorpc.Context()

    class Resolver():
        def resolve_endpoint(self, endpoint):
            if endpoint == 'some_service':
                return test_endpoint
            return endpoint

    class Srv(zerorpc.Server):
        def hello(self):
            print 'heee'
            return 'world'

    srv = Srv(heartbeat=TIME_FACTOR * 1, context=c)
    if sys.version_info < (2, 7):
        assert_raises(zmq.ZMQError, srv.bind, 'some_service')
    else:
        with assert_raises(zmq.ZMQError):
            srv.bind('some_service')

    cnt = c.register_middleware(Resolver())
    assert cnt == 1
    srv.bind('some_service')
    gevent.spawn(srv.run)

    client = zerorpc.Client(heartbeat=TIME_FACTOR * 1, context=c)
    client.connect('some_service')
    assert client.hello() == 'world'

    client.close()
    srv.close()
Exemplo n.º 42
0
def test_sub_events():
    endpoint = random_ipc_endpoint()
    server_events = zerorpc.Events(zmq.ROUTER)
    server_events.bind(endpoint)
    server = zerorpc.ChannelMultiplexer(server_events)

    client_events = zerorpc.Events(zmq.DEALER)
    client_events.connect(endpoint)
    client = zerorpc.ChannelMultiplexer(client_events, ignore_broadcast=True)

    client_channel = client.channel()
    client_channel_events = zerorpc.WrappedEvents(client_channel)
    client_channel_events.emit("coucou", 42)

    event = server.recv()
    print event
    assert type(event.args) is tuple
    assert event.name == "w"
    subevent = event.args
    print "subevent:", subevent
    server_channel = server.channel(event)
    server_channel_events = zerorpc.WrappedEvents(server_channel)
    server_channel_channel = zerorpc.ChannelMultiplexer(server_channel_events)
    event = server_channel_channel.recv()
    print event
    assert event.name == "coucou"
    assert event.args == 42

    server_events.close()
    client_events.close()
def test_hook_client_after_request_timeout():

    class ClientAfterRequestMiddleware(object):
        def __init__(self):
            self.called = False
        def client_after_request(self, req_event, rep_event, exception):
            self.called = True
            assert req_event is not None
            assert req_event.name == "timeout"
            assert rep_event is None

    zero_ctx = zerorpc.Context()
    test_middleware = ClientAfterRequestMiddleware()
    zero_ctx.register_middleware(test_middleware)
    endpoint = random_ipc_endpoint()

    test_server = zerorpc.Server(EchoModule(), context=zero_ctx)
    test_server.bind(endpoint)
    test_server_task = gevent.spawn(test_server.run)

    test_client = zerorpc.Client(timeout=TIME_FACTOR * 1, context=zero_ctx)
    test_client.connect(endpoint)

    assert test_middleware.called == False
    try:
        test_client.timeout("test")
    except zerorpc.TimeoutExpired as ex:
        assert test_middleware.called == True
        assert "timeout" in ex.args[0]

    test_server.stop()
    test_server_task.join()
Exemplo n.º 44
0
def test_client_server_exception():
    endpoint = random_ipc_endpoint()

    class MySrv(zerorpc.Server):

        def raise_something(self, a):
            return a[4]

    srv = MySrv()
    srv.bind(endpoint)
    gevent.spawn(srv.run)

    client = zerorpc.Client(timeout=2)
    client.connect(endpoint)

    if sys.version_info < (2, 7):
        def _do_with_assert_raises():
            print client.raise_something(42)
        assert_raises(zerorpc.RemoteError, _do_with_assert_raises)
    else:
        with assert_raises(zerorpc.RemoteError):
            print client.raise_something(42)
    assert client.raise_something(range(5)) == 4
    client.close()
    srv.close()
def test_hook_client_before_request():

    class ClientBeforeRequestMiddleware(object):
        def __init__(self):
            self.called = False
        def client_before_request(self, event):
            self.called = True
            self.method = event.name

    zero_ctx = zerorpc.Context()
    endpoint = random_ipc_endpoint()

    test_server = zerorpc.Server(EchoModule(), context=zero_ctx)
    test_server.bind(endpoint)
    test_server_task = gevent.spawn(test_server.run)

    test_client = zerorpc.Client(context=zero_ctx)
    test_client.connect(endpoint)

    assert test_client.echo("test") == "echo: test"

    test_middleware = ClientBeforeRequestMiddleware()
    zero_ctx.register_middleware(test_middleware)
    assert test_middleware.called == False
    assert test_client.echo("test") == "echo: test"
    assert test_middleware.called == True
    assert test_middleware.method == 'echo'

    test_server.stop()
    test_server_task.join()
Exemplo n.º 46
0
def test_client_server_client_timeout():
    endpoint = random_ipc_endpoint()

    class MySrv(zerorpc.Server):

        def lolita(self):
            return 42

        def add(self, a, b):
            gevent.sleep(10)
            return a + b

    srv = MySrv()
    srv.bind(endpoint)
    gevent.spawn(srv.run)

    client = zerorpc.Client(timeout=2)
    client.connect(endpoint)

    if sys.version_info < (2, 7):
        assert_raises(zerorpc.TimeoutExpired, client.add, 1, 4)
    else:
        with assert_raises(zerorpc.TimeoutExpired):
            print client.add(1, 4)
    client.close()
    srv.close()
Exemplo n.º 47
0
def test_sub_events():
    endpoint = random_ipc_endpoint()
    server_events = zerorpc.Events(zmq.XREP)
    server_events.bind(endpoint)
    server = zerorpc.ChannelMultiplexer(server_events)

    client_events = zerorpc.Events(zmq.XREQ)
    client_events.connect(endpoint)
    client = zerorpc.ChannelMultiplexer(client_events, ignore_broadcast=True)

    client_channel = client.channel()
    client_channel_events = zerorpc.WrappedEvents(client_channel)
    client_channel_events.emit('coucou', 42)

    event = server.recv()
    print event
    assert type(event.args) is tuple
    assert event.name == 'w'
    subevent = event.args
    print 'subevent:', subevent
    server_channel = server.channel(event)
    server_channel_events = zerorpc.WrappedEvents(server_channel)
    server_channel_channel = zerorpc.ChannelMultiplexer(server_channel_events)
    event = server_channel_channel.recv()
    print event
    assert event.name == 'coucou'
    assert event.args == 42

    server_events.close()
    client_events.close()
Exemplo n.º 48
0
def test_client_server_client_timeout_with_async():
    endpoint = random_ipc_endpoint()

    class MySrv(zerorpc.Server):

        def lolita(self):
            return 42

        def add(self, a, b):
            gevent.sleep(10)
            return a + b

    srv = MySrv()
    srv.bind(endpoint)
    gevent.spawn(srv.run)

    client = zerorpc.Client(timeout=2)
    client.connect(endpoint)

    # 异步和同步的差别?
    async_result = client.add(1, 4, async=True)

    if sys.version_info < (2, 7):
        def _do_with_assert_raises():
            print async_result.get()
        assert_raises(zerorpc.TimeoutExpired, _do_with_assert_raises)
    else:
        with assert_raises(zerorpc.TimeoutExpired):
            print async_result.get()
    client.close()
    srv.close()
Exemplo n.º 49
0
def test_close_client_bufchan():
    endpoint = random_ipc_endpoint()
    server_events = zerorpc.Events(zmq.XREP)
    server_events.bind(endpoint)
    server = zerorpc.ChannelMultiplexer(server_events)

    client_events = zerorpc.Events(zmq.XREQ)
    client_events.connect(endpoint)
    client = zerorpc.ChannelMultiplexer(client_events, ignore_broadcast=True)

    client_channel = client.channel()
    client_hbchan = zerorpc.HeartBeatOnChannel(client_channel, freq=1)
    client_bufchan = zerorpc.BufferedChannel(client_hbchan)
    client_bufchan.emit('openthat', None)

    event = server.recv()
    server_channel = server.channel(event)
    server_hbchan = zerorpc.HeartBeatOnChannel(server_channel, freq=1)
    server_bufchan = zerorpc.BufferedChannel(server_hbchan)
    server_bufchan.recv()

    gevent.sleep(3)
    print 'CLOSE CLIENT SOCKET!!!'
    client_bufchan.close()
    server_hbchan.close()
    client_channel.close()
    with assert_raises(zerorpc.LostRemote):
        server_bufchan.recv()
    print 'SERVER LOST CLIENT :)'
    server_bufchan.close()
    client_hbchan.close()
    server_channel.close()
    server.close()
    client.close()
Exemplo n.º 50
0
def test_client_server_with_async():
    endpoint = random_ipc_endpoint()

    class MySrv(zerorpc.Server):

        def lolita(self):
            return 42

        def add(self, a, b):
            return a + b

    srv = MySrv()
    srv.bind(endpoint)
    gevent.spawn(srv.run)

    client = zerorpc.Client()
    client.connect(endpoint)

    async_result = client.lolita(async=True)

    # 没有timeout, 一直等待结果
    assert async_result.get() == 42

    async_result = client.add(1, 4, async=True)
    assert async_result.get() == 5
Exemplo n.º 51
0
def test_events_channel_client_side_server_send_many():
    endpoint = random_ipc_endpoint()
    server_events = zerorpc.Events(zmq.ROUTER)
    server_events.bind(endpoint)
    server = zerorpc.ChannelMultiplexer(server_events)

    client_events = zerorpc.Events(zmq.DEALER)
    client_events.connect(endpoint)
    client = zerorpc.ChannelMultiplexer(client_events)

    client_channel = client.channel()
    client_channel.emit('giveme', (10, ))

    event = server.recv()
    print event
    assert list(event.args) == [10]
    assert event.identity is not None

    for x in xrange(10):
        reply_event = server.new_event(
            'someanswer', (x, ),
            xheader=dict(response_to=event.header['message_id']))
        reply_event.identity = event.identity
        server.emit_event(reply_event)
    for x in xrange(10):
        event = client_channel.recv()
        assert list(event.args) == [x]
Exemplo n.º 52
0
def test_config_endpoint_2():
    app = Zask(__name__)
    endpoint = random_ipc_endpoint()
    app.config['ZERORPC_SOME_SERVICE'] = {
        '1.0': endpoint,
        'default': '1.0'
    }
    rpc = ZeroRPC(app, middlewares=[CONFIG_ENDPOINT_MIDDLEWARE])

    class Srv(object):
        __version__ = "1.0"
        __service_name__ = "some_service"

        def hello(self):
            return 'world'

    srv = rpc.Server(Srv())
    gevent.spawn(srv.run)

    client = rpc.Client('some_service')
    assert client.hello() == 'world'

    with pytest.raises(MissingConfigException):
        client = rpc.Client('some_service', version='2.0')

    client.close()
    srv.close()
Exemplo n.º 53
0
def test_client_server_detailed_exception():
    endpoint = random_ipc_endpoint()

    class MySrv(zerorpc.Server):
        def raise_error(self):
            raise RuntimeError('oops!')

    srv = MySrv()
    srv.bind(endpoint)
    gevent.spawn(srv.run)

    client = zerorpc.Client(timeout=2)
    client.connect(endpoint)

    with assert_raises(zerorpc.RemoteError):
        print client.raise_error()
    try:
        client.raise_error()
    except zerorpc.RemoteError as e:
        print 'got that:', e
        print 'name', e.name
        print 'msg', e.msg
        assert e.name == 'RuntimeError'
        assert e.msg == 'oops!'

    client.close()
    srv.close()
Exemplo n.º 54
0
def test_hook_server_after_exec_stream():
    zero_ctx = zerorpc.Context()
    endpoint = random_ipc_endpoint()

    test_server = zerorpc.Server(EchoModule(), context=zero_ctx)
    test_server.bind(endpoint)
    test_server_task = gevent.spawn(test_server.run)
    test_client = zerorpc.Client()
    test_client.connect(endpoint)

    # Test without a middleware
    for echo in test_client.echoes("test"):
        assert echo == "echo: test"

    # Test with a middleware
    test_middleware = ServerAfterExecMiddleware()
    zero_ctx.register_middleware(test_middleware)
    assert test_middleware.called == False
    it = test_client.echoes("test")
    assert next(it) == "echo: test"
    assert test_middleware.called == False
    for echo in it:
        assert echo == "echo: test"
    assert test_middleware.called == True
    assert test_middleware.request_event_name == 'echoes'
    assert test_middleware.reply_event_name == 'STREAM_DONE'

    test_server.stop()
    test_server_task.join()
Exemplo n.º 55
0
def test_server_manual():
    endpoint = random_ipc_endpoint()

    class MySrv(zerorpc.Server):
        def lolita(self):
            return 42

        def add(self, a, b):
            return a + b

    srv = MySrv()
    srv.bind(endpoint)
    gevent.spawn(srv.run)

    client_events = zerorpc.Events(zmq.XREQ)
    client_events.connect(endpoint)
    client = zerorpc.ChannelMultiplexer(client_events, ignore_broadcast=True)

    client_channel = client.channel()
    client_channel.emit('lolita', tuple())
    event = client_channel.recv()
    assert event.args == (42, )
    client_channel.close()

    client_channel = client.channel()
    client_channel.emit('add', (1, 2))
    event = client_channel.recv()
    assert event.args == (3, )
    client_channel.close()
    srv.stop()
Exemplo n.º 56
0
def test_hook_server_after_exec_on_error_puller():
    zero_ctx = zerorpc.Context()
    trigger = gevent.event.Event()
    endpoint = random_ipc_endpoint()

    echo_module = BrokenEchoModule(trigger)
    test_server = zerorpc.Puller(echo_module, context=zero_ctx)
    test_server.bind(endpoint)
    test_server_task = gevent.spawn(test_server.run)
    test_client = zerorpc.Pusher()
    test_client.connect(endpoint)

    test_middleware = ServerAfterExecMiddleware()
    zero_ctx.register_middleware(test_middleware)
    assert test_middleware.called == False
    try:
        test_client.echo("test with a middleware")
        trigger.wait(timeout=2)
    except zerorpc.RemoteError:
        pass
    assert echo_module.last_msg == "Raise"
    assert test_middleware.called == False

    test_server.stop()
    test_server_task.join()
Exemplo n.º 57
0
def test_heartbeat_can_open_channel_server_close():
    endpoint = random_ipc_endpoint()
    server_events = zerorpc.Events(zmq.ROUTER)
    server_events.bind(endpoint)
    server = zerorpc.ChannelMultiplexer(server_events)

    client_events = zerorpc.Events(zmq.DEALER)
    client_events.connect(endpoint)
    client = zerorpc.ChannelMultiplexer(client_events, ignore_broadcast=True)

    client_channel = client.channel()
    client_hbchan = zerorpc.HeartBeatOnChannel(client_channel, freq=2)

    event = server.recv()
    server_channel = server.channel(event)
    server_hbchan = zerorpc.HeartBeatOnChannel(server_channel, freq=2)

    gevent.sleep(3)
    print 'CLOSE SERVER SOCKET!!!'
    server_hbchan.close()
    with assert_raises(zerorpc.LostRemote):
        client_hbchan.recv()
    print 'CLIENT LOST SERVER :)'
    client_hbchan.close()
    server.close()
    client.close()
Exemplo n.º 58
0
def test_hook_server_before_exec_puller():
    zero_ctx = zerorpc.Context()
    trigger = gevent.event.Event()
    endpoint = random_ipc_endpoint()

    echo_module = EchoModule(trigger)
    test_server = zerorpc.Puller(echo_module, context=zero_ctx)
    test_server.bind(endpoint)
    test_server_task = gevent.spawn(test_server.run)
    test_client = zerorpc.Pusher()
    test_client.connect(endpoint)

    # Test without a middleware
    test_client.echo("test")
    trigger.wait(timeout=2)
    assert echo_module.last_msg == "echo: test"
    trigger.clear()

    # Test with a middleware
    test_middleware = ServerBeforeExecMiddleware()
    zero_ctx.register_middleware(test_middleware)
    assert test_middleware.called == False
    test_client.echo("test with a middleware")
    trigger.wait(timeout=2)
    assert echo_module.last_msg == "echo: test with a middleware"
    assert test_middleware.called == True

    test_server.stop()
    test_server_task.join()
Exemplo n.º 59
0
def test_events_channel_both_side():
    endpoint = random_ipc_endpoint()
    server_events = zerorpc.Events(zmq.XREP)
    server_events.bind(endpoint)
    server = zerorpc.ChannelMultiplexer(server_events)

    client_events = zerorpc.Events(zmq.XREQ)
    client_events.connect(endpoint)
    client = zerorpc.ChannelMultiplexer(client_events)

    client_channel = client.channel()
    client_channel.emit('openthat', (42,))

    event = server.recv()
    print event
    assert event.args == (42,)
    assert event.name == 'openthat'

    server_channel = server.channel(event)
    server_channel.emit('test', (21,))

    event = client_channel.recv()
    assert event.args == (21,)
    assert event.name == 'test'

    server_channel.emit('test', (22,))

    event = client_channel.recv()
    assert event.args == (22,)
    assert event.name == 'test'

    server_events.close()
    server_channel.close()
    client_channel.close()
    client_events.close()
Exemplo n.º 60
0
def test_heartbeat_can_open_channel_client_close():
    endpoint = random_ipc_endpoint()
    server_events = zerorpc.Events(zmq.ROUTER)
    server_events.bind(endpoint)
    server = zerorpc.ChannelMultiplexer(server_events)

    client_events = zerorpc.Events(zmq.DEALER)
    client_events.connect(endpoint)
    client = zerorpc.ChannelMultiplexer(client_events, ignore_broadcast=True)

    client_channel = client.channel()
    client_hbchan = zerorpc.HeartBeatOnChannel(client_channel, freq=2)

    event = server.recv()
    server_channel = server.channel(event)
    server_hbchan = zerorpc.HeartBeatOnChannel(server_channel, freq=2)

    gevent.sleep(3)
    print 'CLOSE CLIENT SOCKET!!!'
    client_hbchan.close()
    client.close()
    with assert_raises(zerorpc.LostRemote):
        server_hbchan.recv()
    print 'SERVER LOST CLIENT :)'
    server_hbchan.close()
    server.close()