def test_zipkin_trace(trace_server):
    endpoint = b'endpoint1'
    zipkin_tracer = ZipkinTraceHook(dst=trace_buf)
    tchannel = TChannel(name='test')
    tchannel.hooks.register(zipkin_tracer)

    hostport = 'localhost:%d' % trace_server.port

    response = yield tchannel.request(hostport).send(InMemStream(endpoint),
                                                     InMemStream(hostport),
                                                     InMemStream(),
                                                     traceflag=True)
    header = yield response.get_header()
    body = yield response.get_body()
    assert header == "from handler1"
    assert body == "from handler2"
    traces = []
    for trace in trace_buf.getvalue().split("\n"):
        if trace:
            traces.append(json.loads(trace))

    trace_id = traces[0][0][u'trace_id']
    for trace in traces:
        assert trace_id == trace[0][u'trace_id']
        if trace[0][u'name'] == u'endpoint2':
            parent_span_id = trace[0][u'parent_span_id']
        else:
            span_id = trace[0][u'span_id']

    assert parent_span_id == span_id
예제 #2
0
def test_zipkin_trace(trace_server):
    endpoint = b'endpoint1'
    zipkin_tracer = ZipkinTraceHook(dst=trace_buf)
    tchannel = TChannel(name='test')
    tchannel.hooks.register(zipkin_tracer)

    hostport = 'localhost:%d' % trace_server.port

    response = yield tchannel.request(hostport).send(InMemStream(endpoint),
                                                     InMemStream(hostport),
                                                     InMemStream(),
                                                     traceflag=True)
    header = yield response.get_header()
    body = yield response.get_body()
    assert header == "from handler1"
    assert body == "from handler2"
    traces = []
    for trace in trace_buf.getvalue().split("\n"):
        if trace:
            traces.append(json.loads(trace))

    trace_id = traces[0][0][u'trace_id']
    for trace in traces:
        assert trace_id == trace[0][u'trace_id']
        if trace[0][u'name'] == u'endpoint2':
            parent_span_id = trace[0][u'parent_span_id']
        else:
            span_id = trace[0][u'span_id']

    assert parent_span_id == span_id
예제 #3
0
def test_endpoint_not_found(mock_server):
    endpoint = b'tchanneltest'
    mock_server.expect_call(endpoint).and_write(headers=endpoint, body='world')
    tchannel = TChannel(name='test')

    with pytest.raises(TChannelError):
        yield tchannel.request(mock_server.hostport).send(
            InMemStream(), InMemStream(), InMemStream())
예제 #4
0
def test_request():
    channel = TChannel(name="test")
    hyperbahn.advertise(channel, "foo", ["127.0.0.1:23000"])

    # Just want to make sure all the plumbing fits together.

    with pytest.raises(NoAvailablePeerError):
        yield channel.request(service="bar").send(arg1="baz", arg2="bam", arg3="boo", headers={"as": "qux"})
예제 #5
0
def test_endpoint_not_found(tchannel_server):
    endpoint = b"tchanneltest"
    tchannel_server.expect_call(endpoint).and_write(headers=endpoint, body="world")
    tchannel = TChannel(name="test")

    hostport = "localhost:%d" % (tchannel_server.port)

    with pytest.raises(TChannelError):
        yield tchannel.request(hostport).send(InMemStream(), InMemStream(), InMemStream())
def send_stream(arg1, arg2, arg3, host):
    tchannel = TChannel(
        name='stream-client',
    )

    yield tchannel.request(host).send(
        arg1,
        arg2,
        arg3,
    )
예제 #7
0
def send_stream(arg1, arg2, arg3, host):
    tchannel = TChannel()
    response = yield tchannel.request(host).send(
        arg1,
        arg2,
        arg3)

    yield print_arg(response, 0)
    yield print_arg(response, 1)
    yield print_arg(response, 2)
예제 #8
0
def test_request():
    channel = TChannel()
    hyperbahn.advertise(channel, 'foo', ['127.0.0.1:23000'])

    # Just want to make sure all the plumbing fits together.
    with pytest.raises(ConnectionClosedError):
        yield channel.request(service='bar').send(
            arg1='baz',
            arg2='bam',
            arg3='boo',
            headers={'as': 'qux'},
        )
def test_endpoint_not_found(mock_server):
    endpoint = b'tchanneltest'
    mock_server.expect_call(endpoint).and_write(
        headers=endpoint,
        body='world'
    )
    tchannel = TChannel(name='test')

    with pytest.raises(TChannelError):
        yield tchannel.request(
            mock_server.hostport
        ).send(InMemStream(), InMemStream(), InMemStream())
예제 #10
0
def test_request():
    channel = TChannel(name='test')
    hyperbahn.advertise(channel, 'foo', ['127.0.0.1:23000'])

    # Just want to make sure all the plumbing fits together.

    with pytest.raises(ConnectionClosedError):
        yield channel.request(service='bar').send(
            arg1='baz',
            arg2='bam',
            arg3='boo',
            headers={'as': 'qux'},
        )
예제 #11
0
def main():

    args = get_args()

    tchannel = TChannel(name="raw-client")

    request = tchannel.request(hostport="%s:%s" % (args.host, args.port))

    response = yield request.send("hi", None, None)

    body = yield response.get_body()

    print body
예제 #12
0
def test_tchannel_call_request_fragment(mock_server, arg2, arg3):
    endpoint = b'tchannelpeertest'

    mock_server.expect_call(endpoint).and_write(headers=endpoint, body=arg3)

    tchannel = TChannel(name='test')
    response = yield tchannel.request(mock_server.hostport).send(
        InMemStream(endpoint), InMemStream(arg2), InMemStream(arg3))
    header = yield response.get_header()
    body = yield response.get_body()
    assert header == endpoint
    assert body == arg3
    assert response.headers['as'] == 'raw'
예제 #13
0
def test_endpoint_not_found(tchannel_server):
    endpoint = b'tchanneltest'
    tchannel_server.expect_call(endpoint).and_write(
        headers=endpoint,
        body='world'
    )
    tchannel = TChannel()

    hostport = 'localhost:%d' % (tchannel_server.port)

    with pytest.raises(TChannelError):
        yield tchannel.request(hostport).send(InMemStream(),
                                              InMemStream(),
                                              InMemStream())
예제 #14
0
def test_tchannel_call_request_fragment(tchannel_server, arg2, arg3):
    endpoint = b"tchannelpeertest"

    tchannel_server.expect_call(endpoint).and_write(headers=endpoint, body=arg3)

    tchannel = TChannel(name="test")

    hostport = "localhost:%d" % (tchannel_server.port)

    response = yield tchannel.request(hostport).send(InMemStream(endpoint), InMemStream(arg2), InMemStream(arg3))
    header = yield response.get_header()
    body = yield response.get_body()
    assert header == endpoint
    assert body == arg3
    assert response.headers["as"] == "raw"
예제 #15
0
def test_tchannel_call_request_fragment(mock_server,
                                        arg2, arg3):
    endpoint = b'tchannelpeertest'

    mock_server.expect_call(endpoint).and_write(
        headers=endpoint, body=arg3
    )

    tchannel = TChannel(name='test')
    response = yield tchannel.request(mock_server.hostport).send(
        InMemStream(endpoint), InMemStream(arg2), InMemStream(arg3)
    )
    header = yield response.get_header()
    body = yield response.get_body()
    assert header == endpoint
    assert body == arg3
    assert response.headers['as'] == 'raw'
def test_false_result(thrift_service):
    # Verify that we aren't treating False as None.

    app = TChannel(name='app')

    @app.register(thrift_service)
    def healthy(request, response):
        return False

    app.listen()

    client = TChannel(name='client')
    response = yield client.request(hostport=app.hostport,
                                    arg_scheme='thrift').send(
                                        'Service::healthy', '\x00\x00', '\x00')

    body = yield response.get_body()
    assert body == '\x02\x00\x00\x00\x00'
def test_false_result(thrift_service):
    # Verify that we aren't treating False as None.

    app = TChannel(name='app')

    @app.register(thrift_service)
    def healthy(request, response):
        return False

    app.listen()

    client = TChannel(name='client')
    response = yield client.request(
        hostport=app.hostport, arg_scheme='thrift'
    ).send('Service::healthy', '\x00\x00', '\x00')

    body = yield response.get_body()
    assert body == '\x02\x00\x00\x00\x00'
예제 #18
0
def test_json_server(json_server, sample_json):
    endpoint = "json_echo"
    tchannel = TChannel(name='test')
    hostport = 'localhost:%d' % json_server.port
    client = tchannel.request(hostport)
    header = sample_json
    body = sample_json
    resp = yield ArgSchemeBroker(JsonArgScheme()).send(
        client,
        endpoint,
        header,
        body,
    )

    # compare header's json
    rheader = yield resp.get_header()
    assert rheader == header

    # compare body's json
    rbody = yield resp.get_body()
    assert rbody == body
def test_json_server(json_server, sample_json):
    endpoint = "json_echo"
    tchannel = TChannel(name='test')
    client = tchannel.request(json_server.hostport)
    header = sample_json
    body = sample_json
    resp = yield ArgSchemeBroker(JsonArgScheme()).send(
        client,
        endpoint,
        header,
        body,
    )

    # check protocol header
    assert resp.headers['as'] == 'json'
    # compare header's json
    rheader = yield resp.get_header()
    assert rheader == header

    # compare body's json
    rbody = yield resp.get_body()
    assert rbody == body
예제 #20
0
def test_patching_as_context_manager():
    chan = TChannel('client')
    with Patcher('localhost:4040'):
        ops = chan.request(service='foo')
        assert isinstance(ops, PatchedClientOperation)
        assert ops.vcr_hostport == 'localhost:4040'
예제 #21
0
class VCRProxyService(object):
    def __init__(self, cassette, unpatch):
        """
        :param unpatch:
            A function returning a context manager which temporarily unpatches
            any monkey patched code so that a real request can be made.
        :param cassette:
            Cassette being played.
        """
        self.unpatch = unpatch
        self.cassette = cassette

        self.tchannel = TChannel("proxy-server")
        self.tchannel.register(VCRProxy, handler=self.send)

    @wrap_uncaught(
        reraise=(VCRProxy.CannotRecordInteractionsError, VCRProxy.RemoteServiceError, VCRProxy.VCRServiceError)
    )
    @gen.coroutine
    def send(self, request, response):
        cassette = self.cassette
        request = request.args.request

        # TODO decode requests and responses based on arg scheme into more
        # readable formats.

        # Because Thrift doesn't handle UTF-8 correctly right now
        request.serviceName = request.serviceName.decode("utf-8")
        request.endpoint = request.endpoint.decode("utf-8")

        # TODO do we care about hostport being the same?
        if cassette.can_replay(request):
            vcr_response = cassette.replay(request)
            raise gen.Return(vcr_response)

        if cassette.write_protected:
            raise VCRProxy.CannotRecordInteractionsError(
                "Could not find a matching response for request %s and the "
                "record mode %s prevents new interactions from being "
                "recorded. Your test may be performing an uenxpected "
                "request." % (str(request), cassette.record_mode)
            )

        arg_scheme = VCRProxy.ArgScheme.to_name(request.argScheme).lower()

        with self.unpatch():
            # TODO propagate other request and response parameters
            # TODO might make sense to tag all VCR requests with a protocol
            # header of some kind
            response_future = self.tchannel.request(
                service=request.serviceName, arg_scheme=arg_scheme, hostport=request.hostPort
            ).send(
                request.endpoint,
                request.headers,
                request.body,
                headers={h.key: h.value for h in request.transportHeaders},
            )

        # Don't actually yield while everything is unpatched.
        try:
            response = yield response_future
        except TChannelError as e:
            raise VCRProxy.RemoteServiceError(code=e.code, message=e.message)
        response_headers = yield response.get_header()
        response_body = yield response.get_body()

        vcr_response = VCRProxy.Response(response.status_code, response_headers, response_body)
        cassette.record(request, vcr_response)
        raise gen.Return(vcr_response)

    @property
    def hostport(self):
        return self.tchannel.hostport

    def start(self):
        self.tchannel.listen()

    def stop(self):
        self.tchannel.close()

    def __enter__(self):
        self.start()
        return self

    def __exit__(self, *args):
        self.stop()
예제 #22
0
class VCRProxyService(object):
    def __init__(self, cassette, unpatch):
        """
        :param unpatch:
            A function returning a context manager which temporarily unpatches
            any monkey patched code so that a real request can be made.
        :param cassette:
            Cassette being played.
        """
        self.unpatch = unpatch
        self.cassette = cassette

        self.tchannel = TChannel('proxy-server')
        self.tchannel.register(VCRProxy, handler=self.send)

    @wrap_uncaught(reraise=(
        VCRProxy.CannotRecordInteractionsError,
        VCRProxy.RemoteServiceError,
        VCRProxy.VCRServiceError,
    ))
    @gen.coroutine
    def send(self, request, response):
        cassette = self.cassette
        request = request.args.request

        # TODO decode requests and responses based on arg scheme into more
        # readable formats.

        # Because Thrift doesn't handle UTF-8 correctly right now
        request.serviceName = request.serviceName.decode('utf-8')
        request.endpoint = request.endpoint.decode('utf-8')

        # TODO do we care about hostport being the same?
        if cassette.can_replay(request):
            vcr_response = cassette.replay(request)
            raise gen.Return(vcr_response)

        if cassette.write_protected:
            raise VCRProxy.CannotRecordInteractionsError(
                'Could not find a matching response for request %s and the '
                'record mode %s prevents new interactions from being '
                'recorded. Your test may be performing an uenxpected '
                'request.' % (str(request), cassette.record_mode))

        arg_scheme = VCRProxy.ArgScheme.to_name(request.argScheme).lower()

        with self.unpatch():
            # TODO propagate other request and response parameters
            # TODO might make sense to tag all VCR requests with a protocol
            # header of some kind
            response_future = self.tchannel.request(
                service=request.serviceName,
                arg_scheme=arg_scheme,
                hostport=request.hostPort,
            ).send(
                request.endpoint,
                request.headers,
                request.body,
                headers={h.key: h.value
                         for h in request.transportHeaders},
            )

        # Don't actually yield while everything is unpatched.
        try:
            response = yield response_future
        except ProtocolError as e:
            raise VCRProxy.RemoteServiceError(
                code=e.code,
                message=e.message,
            )
        response_headers = yield response.get_header()
        response_body = yield response.get_body()

        vcr_response = VCRProxy.Response(
            response.status_code,
            response_headers,
            response_body,
        )
        cassette.record(request, vcr_response)
        raise gen.Return(vcr_response)

    @property
    def hostport(self):
        return self.tchannel.hostport

    def start(self):
        self.tchannel.listen()

    def stop(self):
        self.tchannel.close()

    def __enter__(self):
        self.start()
        return self

    def __exit__(self, *args):
        self.stop()
예제 #23
0
def test_patching_as_context_manager(vcr_client):
    chan = TChannel('client')
    with Patcher(vcr_client):
        ops = chan.request(service='foo')
        assert isinstance(ops, PatchedClientOperation)
        assert ops.vcr_client is vcr_client