async def test_response_caching(self):
        # Prepares a preset value to help testing
        interceptor = _CacheInterceptor({
            42:
            messages_pb2.SimpleResponse(payload=messages_pb2.Payload(
                body=b'\x42'))
        })

        # Constructs a server with the cache interceptor
        server, stub = await _create_server_stub_pair(interceptor)

        # Tests if the cache store is used
        response = await stub.UnaryCall(
            messages_pb2.SimpleRequest(response_size=42))
        self.assertEqual(1, len(interceptor.cache_store[42].payload.body))
        self.assertEqual(interceptor.cache_store[42], response)

        # Tests response can be cached
        response = await stub.UnaryCall(
            messages_pb2.SimpleRequest(response_size=1337))
        self.assertEqual(1337, len(interceptor.cache_store[1337].payload.body))
        self.assertEqual(interceptor.cache_store[1337], response)
        response = await stub.UnaryCall(
            messages_pb2.SimpleRequest(response_size=1337))
        self.assertEqual(interceptor.cache_store[1337], response)
    async def test_channel_isolation(self):
        async with aio.insecure_channel(self._server_target) as channel1:
            async with aio.insecure_channel(self._server_target) as channel2:
                stub1 = test_pb2_grpc.TestServiceStub(channel1)
                stub2 = test_pb2_grpc.TestServiceStub(channel2)

                call1 = stub1.UnaryCall(messages_pb2.SimpleRequest())
                call2 = stub2.UnaryCall(messages_pb2.SimpleRequest())

            self.assertFalse(call1.cancelled())
            self.assertTrue(call2.cancelled())
Beispiel #3
0
    def __init__(self, server, config, hist):
        # Create the stub
        host, port = server.split(':')
        port = int(port)
        if config.HasField('security_params'):
            creds = implementations.ssl_channel_credentials(
                resources.test_root_certificates())
            channel = test_utilities.not_really_secure_channel(
                host, port, creds, config.security_params.server_host_override)
        else:
            channel = implementations.insecure_channel(host, port)

        if config.payload_config.WhichOneof('payload') == 'simple_params':
            self._generic = False
            self._stub = services_pb2.beta_create_BenchmarkService_stub(
                channel)
            payload = messages_pb2.Payload(
                body='\0' * config.payload_config.simple_params.req_size)
            self._request = messages_pb2.SimpleRequest(
                payload=payload,
                response_size=config.payload_config.simple_params.resp_size)
        else:
            self._generic = True
            self._stub = implementations.generic_stub(channel)
            self._request = '\0' * config.payload_config.bytebuf_params.req_size

        self._hist = hist
        self._response_callbacks = []
Beispiel #4
0
        async def coro():
            server_target, _ = await start_test_server()  # pylint: disable=unused-variable

            async with aio.insecure_channel(server_target) as channel:
                empty_call_with_sleep = channel.unary_unary(
                    _EMPTY_CALL_METHOD,
                    request_serializer=messages_pb2.SimpleRequest.
                    SerializeToString,
                    response_deserializer=messages_pb2.SimpleResponse.
                    FromString,
                )
                timeout = test_constants.SHORT_TIMEOUT / 2
                # TODO(https://github.com/grpc/grpc/issues/20869)
                # Update once the async server is ready, change the
                # synchronization mechanism by removing the sleep(<timeout>)
                # as both components (client & server) will be on the same
                # process.
                with self.assertRaises(grpc.RpcError) as exception_context:
                    await empty_call_with_sleep(messages_pb2.SimpleRequest(),
                                                timeout=timeout)

                _, details = grpc.StatusCode.DEADLINE_EXCEEDED.value  # pylint: disable=unused-variable
                self.assertEqual(exception_context.exception.code(),
                                 grpc.StatusCode.DEADLINE_EXCEEDED)
                self.assertEqual(exception_context.exception.details(),
                                 details.title())
                self.assertIsNotNone(
                    exception_context.exception.initial_metadata())
                self.assertIsNotNone(
                    exception_context.exception.trailing_metadata())
Beispiel #5
0
def _status_code_and_message(stub):
    message = 'test status message'
    code = 2
    status = grpc.StatusCode.UNKNOWN  # code = 2
    request = messages_pb2.SimpleRequest(
        response_type=messages_pb2.COMPRESSABLE,
        response_size=1,
        payload=messages_pb2.Payload(body=b'\x00'),
        response_status=messages_pb2.EchoStatus(code=code, message=message))
    response_future = stub.UnaryCall.future(request)
    if response_future.code() != status:
        raise ValueError('expected code %s, got %s' %
                         (status, response_future.code()))
    elif response_future.details() != message:
        raise ValueError('expected message %s, got %s' %
                         (message, response_future.details()))

    request = messages_pb2.StreamingOutputCallRequest(
        response_type=messages_pb2.COMPRESSABLE,
        response_parameters=(messages_pb2.ResponseParameters(size=1), ),
        response_status=messages_pb2.EchoStatus(code=code, message=message))
    response_iterator = stub.StreamingOutputCall(request)
    if response_future.code() != status:
        raise ValueError('expected code %s, got %s' %
                         (status, response_iterator.code()))
    elif response_future.details() != message:
        raise ValueError('expected message %s, got %s' %
                         (message, response_iterator.details()))
Beispiel #6
0
    async def test_initial_metadata_modification(self):
        class Interceptor(aio.UnaryUnaryClientInterceptor):
            async def intercept_unary_unary(self, continuation,
                                            client_call_details, request):
                new_details = aio.ClientCallDetails(
                    method=client_call_details.method,
                    timeout=client_call_details.timeout,
                    metadata=client_call_details.metadata +
                    _INITIAL_METADATA_TO_INJECT,
                    credentials=client_call_details.credentials,
                    wait_for_ready=client_call_details.wait_for_ready,
                )
                return await continuation(new_details, request)

        async with aio.insecure_channel(self._server_target,
                                        interceptors=[Interceptor()
                                                      ]) as channel:
            stub = test_pb2_grpc.TestServiceStub(channel)
            call = stub.UnaryCall(messages_pb2.SimpleRequest())

            # Expected to see the echoed initial metadata
            self.assertTrue(
                _common.seen_metadatum(_INITIAL_METADATA_TO_INJECT[0], await
                                       call.initial_metadata()))

            # Expected to see the echoed trailing metadata
            self.assertTrue(
                _common.seen_metadatum(_INITIAL_METADATA_TO_INJECT[1], await
                                       call.trailing_metadata()))

            self.assertEqual(await call.code(), grpc.StatusCode.OK)
Beispiel #7
0
    async def test_retry(self):
        class RetryInterceptor(aio.UnaryUnaryClientInterceptor):
            """Simulates a Retry Interceptor which ends up by making 
            two RPC calls."""
            def __init__(self):
                self.calls = []

            async def intercept_unary_unary(self, continuation,
                                            client_call_details, request):

                new_client_call_details = aio.ClientCallDetails(
                    method=client_call_details.method,
                    timeout=_constants.UNARY_CALL_WITH_SLEEP_VALUE / 2,
                    metadata=client_call_details.metadata,
                    credentials=client_call_details.credentials,
                    wait_for_ready=client_call_details.wait_for_ready)

                try:
                    call = await continuation(new_client_call_details, request)
                    await call
                except grpc.RpcError:
                    pass

                self.calls.append(call)

                new_client_call_details = aio.ClientCallDetails(
                    method=client_call_details.method,
                    timeout=None,
                    metadata=client_call_details.metadata,
                    credentials=client_call_details.credentials,
                    wait_for_ready=client_call_details.wait_for_ready)

                call = await continuation(new_client_call_details, request)
                self.calls.append(call)
                return call

        interceptor = RetryInterceptor()

        async with aio.insecure_channel(self._server_target,
                                        interceptors=[interceptor]) as channel:

            multicallable = channel.unary_unary(
                '/grpc.testing.TestService/UnaryCallWithSleep',
                request_serializer=messages_pb2.SimpleRequest.
                SerializeToString,
                response_deserializer=messages_pb2.SimpleResponse.FromString)

            call = multicallable(messages_pb2.SimpleRequest())

            await call

            self.assertEqual(grpc.StatusCode.OK, await call.code())

            # Check that two calls were made, first one finishing with
            # a deadline and second one finishing ok..
            self.assertEqual(len(interceptor.calls), 2)
            self.assertEqual(await interceptor.calls[0].code(),
                             grpc.StatusCode.DEADLINE_EXCEEDED)
            self.assertEqual(await interceptor.calls[1].code(),
                             grpc.StatusCode.OK)
Beispiel #8
0
 async def test_async_context(self):
     async with aio.insecure_channel(self._server_target) as channel:
         hi = channel.unary_unary(
             _UNARY_CALL_METHOD,
             request_serializer=messages_pb2.SimpleRequest.SerializeToString,
             response_deserializer=messages_pb2.SimpleResponse.FromString)
         await hi(messages_pb2.SimpleRequest())
Beispiel #9
0
    def test_graceful_close(self):
        stub = test_pb2_grpc.TestServiceStub(self._channel)
        _, response = stub.UnaryCall.with_call(messages_pb2.SimpleRequest())

        self._channel.close()

        self.assertEqual(grpc.StatusCode.OK, response.code())
Beispiel #10
0
    async def test_call_rpc_error(self):
        async with aio.insecure_channel(_UNREACHABLE_TARGET) as channel:
            hi = channel.unary_unary(
                '/grpc.testing.TestService/UnaryCall',
                request_serializer=messages_pb2.SimpleRequest.SerializeToString,
                response_deserializer=messages_pb2.SimpleResponse.FromString,
            )

            call = hi(messages_pb2.SimpleRequest(), timeout=0.1)

            with self.assertRaises(grpc.RpcError) as exception_context:
                await call

            self.assertEqual(grpc.StatusCode.DEADLINE_EXCEEDED,
                             exception_context.exception.code())

            self.assertTrue(call.done())
            self.assertEqual(grpc.StatusCode.DEADLINE_EXCEEDED, await
                             call.code())

            # Exception is cached at call object level, reentrance
            # returns again the same exception
            with self.assertRaises(grpc.RpcError) as exception_context_retry:
                await call

            self.assertIs(exception_context.exception,
                          exception_context_retry.exception)
Beispiel #11
0
def _status_code_and_message(stub):
    details = 'test status message'
    code = 2
    status = grpc.StatusCode.UNKNOWN  # code = 2

    # Test with a UnaryCall
    request = messages_pb2.SimpleRequest(
        response_type=messages_pb2.COMPRESSABLE,
        response_size=1,
        payload=messages_pb2.Payload(body=b'\x00'),
        response_status=messages_pb2.EchoStatus(code=code, message=details))
    response_future = stub.UnaryCall.future(request)
    _validate_status_code_and_details(response_future, status, details)

    # Test with a FullDuplexCall
    with _Pipe() as pipe:
        response_iterator = stub.FullDuplexCall(pipe)
        request = messages_pb2.StreamingOutputCallRequest(
            response_type=messages_pb2.COMPRESSABLE,
            response_parameters=(messages_pb2.ResponseParameters(size=1), ),
            payload=messages_pb2.Payload(body=b'\x00'),
            response_status=messages_pb2.EchoStatus(code=code,
                                                    message=details))
        pipe.add(request)  # sends the initial request.
    # Dropping out of with block closes the pipe
    _validate_status_code_and_details(response_iterator, status, details)
Beispiel #12
0
    async def test_add_timeout(self):

        class TimeoutInterceptor(aio.UnaryUnaryClientInterceptor):
            """Interceptor used for adding a timeout to the RPC"""

            async def intercept_unary_unary(self, continuation,
                                            client_call_details, request):
                new_client_call_details = aio.ClientCallDetails(
                    method=client_call_details.method,
                    timeout=UNARY_CALL_WITH_SLEEP_VALUE / 2,
                    metadata=client_call_details.metadata,
                    credentials=client_call_details.credentials)
                return await continuation(new_client_call_details, request)

        interceptor = TimeoutInterceptor()

        async with aio.insecure_channel(self._server_target,
                                        interceptors=[interceptor]) as channel:

            multicallable = channel.unary_unary(
                '/grpc.testing.TestService/UnaryCallWithSleep',
                request_serializer=messages_pb2.SimpleRequest.SerializeToString,
                response_deserializer=messages_pb2.SimpleResponse.FromString)

            call = multicallable(messages_pb2.SimpleRequest())

            with self.assertRaises(aio.AioRpcError) as exception_context:
                await call

            self.assertEqual(exception_context.exception.code(),
                             grpc.StatusCode.DEADLINE_EXCEEDED)

            self.assertTrue(call.done())
            self.assertEqual(grpc.StatusCode.DEADLINE_EXCEEDED, await
                             call.code())
Beispiel #13
0
        async def coro():
            async with aio.insecure_channel(self.server_target) as channel:
                empty_call_with_sleep = channel.unary_unary(
                    "/grpc.testing.TestService/EmptyCall",
                    request_serializer=messages_pb2.SimpleRequest.
                    SerializeToString,
                    response_deserializer=messages_pb2.SimpleResponse.
                    FromString,
                )
                timeout = test_constants.SHORT_TIMEOUT / 2
                # TODO: Update once the async server is ready, change the synchronization mechanism by removing the
                # sleep(<timeout>) as both components (client & server) will be on the same process.
                with self.assertRaises(grpc.RpcError) as exception_context:
                    await empty_call_with_sleep(messages_pb2.SimpleRequest(),
                                                timeout=timeout)

                status_code, details = grpc.StatusCode.DEADLINE_EXCEEDED.value
                self.assertEqual(exception_context.exception.code(),
                                 status_code)
                self.assertEqual(exception_context.exception.details(),
                                 details.title())
                self.assertIsNotNone(
                    exception_context.exception.initial_metadata())
                self.assertIsNotNone(
                    exception_context.exception.trailing_metadata())
Beispiel #14
0
    async def test_call_rpc_error(self):
        async with aio.insecure_channel(self._server_target) as channel:
            empty_call_with_sleep = channel.unary_unary(
                "/grpc.testing.TestService/EmptyCall",
                request_serializer=messages_pb2.SimpleRequest.
                SerializeToString,
                response_deserializer=messages_pb2.SimpleResponse.FromString,
            )
            timeout = test_constants.SHORT_TIMEOUT / 2
            # TODO(https://github.com/grpc/grpc/issues/20869
            # Update once the async server is ready, change the
            # synchronization mechanism by removing the sleep(<timeout>)
            # as both components (client & server) will be on the same
            # process.
            call = empty_call_with_sleep(messages_pb2.SimpleRequest(),
                                         timeout=timeout)

            with self.assertRaises(grpc.RpcError) as exception_context:
                await call

            self.assertEqual(grpc.StatusCode.DEADLINE_EXCEEDED,
                             exception_context.exception.code())

            self.assertTrue(call.done())
            self.assertEqual(grpc.StatusCode.DEADLINE_EXCEEDED, await
                             call.code())

            # Exception is cached at call object level, reentrance
            # returns again the same exception
            with self.assertRaises(grpc.RpcError) as exception_context_retry:
                await call

            self.assertIs(exception_context.exception,
                          exception_context_retry.exception)
Beispiel #15
0
async def _status_code_and_message(stub: test_pb2_grpc.TestServiceStub):
    details = 'test status message'
    status = grpc.StatusCode.UNKNOWN  # code = 2

    # Test with a UnaryCall
    request = messages_pb2.SimpleRequest(
        response_type=messages_pb2.COMPRESSABLE,
        response_size=1,
        payload=messages_pb2.Payload(body=b'\x00'),
        response_status=messages_pb2.EchoStatus(code=status.value[0],
                                                message=details))
    call = stub.UnaryCall(request)
    await _validate_status_code_and_details(call, status, details)

    # Test with a FullDuplexCall
    call = stub.FullDuplexCall()
    request = messages_pb2.StreamingOutputCallRequest(
        response_type=messages_pb2.COMPRESSABLE,
        response_parameters=(messages_pb2.ResponseParameters(size=1),),
        payload=messages_pb2.Payload(body=b'\x00'),
        response_status=messages_pb2.EchoStatus(code=status.value[0],
                                                message=details))
    await call.write(request)  # sends the initial request.
    await call.done_writing()
    await _validate_status_code_and_details(call, status, details)
Beispiel #16
0
    def __init__(self, server, config, hist):
        # Create the stub
        if config.HasField('security_params'):
            creds = grpc.ssl_channel_credentials(
                resources.test_root_certificates())
            channel = test_common.test_secure_channel(
                server, creds, config.security_params.server_host_override)
        else:
            channel = grpc.insecure_channel(server)

        # waits for the channel to be ready before we start sending messages
        grpc.channel_ready_future(channel).result()

        if config.payload_config.WhichOneof('payload') == 'simple_params':
            self._generic = False
            self._stub = benchmark_service_pb2_grpc.BenchmarkServiceStub(
                channel)
            payload = messages_pb2.Payload(
                body=bytes(b'\0' *
                           config.payload_config.simple_params.req_size))
            self._request = messages_pb2.SimpleRequest(
                payload=payload,
                response_size=config.payload_config.simple_params.resp_size)
        else:
            self._generic = True
            self._stub = GenericStub(channel)
            self._request = bytes(b'\0' *
                                  config.payload_config.bytebuf_params.req_size)

        self._hist = hist
        self._response_callbacks = []
Beispiel #17
0
async def _custom_metadata(stub: test_pb2_grpc.TestServiceStub):
    initial_metadata_value = "test_initial_metadata_value"
    trailing_metadata_value = b"\x0a\x0b\x0a\x0b\x0a\x0b"
    metadata = ((_INITIAL_METADATA_KEY, initial_metadata_value),
                (_TRAILING_METADATA_KEY, trailing_metadata_value))

    async def _validate_metadata(call):
        initial_metadata = dict(await call.initial_metadata())
        if initial_metadata[_INITIAL_METADATA_KEY] != initial_metadata_value:
            raise ValueError('expected initial metadata %s, got %s' %
                             (initial_metadata_value,
                              initial_metadata[_INITIAL_METADATA_KEY]))
        trailing_metadata = dict(await call.trailing_metadata())
        if trailing_metadata[_TRAILING_METADATA_KEY] != trailing_metadata_value:
            raise ValueError('expected trailing metadata %s, got %s' %
                             (trailing_metadata_value,
                              trailing_metadata[_TRAILING_METADATA_KEY]))

    # Testing with UnaryCall
    request = messages_pb2.SimpleRequest(
        response_type=messages_pb2.COMPRESSABLE,
        response_size=1,
        payload=messages_pb2.Payload(body=b'\x00'))
    call = stub.UnaryCall(request, metadata=metadata)
    await _validate_metadata(call)

    # Testing with FullDuplexCall
    call = stub.FullDuplexCall(metadata=metadata)
    request = messages_pb2.StreamingOutputCallRequest(
        response_type=messages_pb2.COMPRESSABLE,
        response_parameters=(messages_pb2.ResponseParameters(size=1),))
    await call.write(request)
    await call.read()
    await call.done_writing()
    await _validate_metadata(call)
Beispiel #18
0
    async def test_add_done_callback_after_finishes_before_await(self):
        called = asyncio.Event()

        def callback(call):
            called.set()

        class Interceptor(aio.UnaryUnaryClientInterceptor):

            async def intercept_unary_unary(self, continuation,
                                            client_call_details, request):

                call = await continuation(client_call_details, request)
                return call

        async with aio.insecure_channel(self._server_target,
                                        interceptors=[Interceptor()
                                                     ]) as channel:

            multicallable = channel.unary_unary(
                '/grpc.testing.TestService/UnaryCall',
                request_serializer=messages_pb2.SimpleRequest.SerializeToString,
                response_deserializer=messages_pb2.SimpleResponse.FromString)
            call = multicallable(messages_pb2.SimpleRequest())

            call.add_done_callback(callback)

            await call

            try:
                await asyncio.wait_for(
                    called.wait(),
                    timeout=_TIMEOUT_CHECK_IF_CALLBACK_WAS_CALLED)
            except:
                self.fail("Callback was not called")
Beispiel #19
0
    async def test_status_code_Ok(self):

        class StatusCodeOkInterceptor(aio.UnaryUnaryClientInterceptor):
            """Interceptor used for observing status code Ok returned by the RPC"""

            def __init__(self):
                self.status_code_Ok_observed = False

            async def intercept_unary_unary(self, continuation,
                                            client_call_details, request):
                call = await continuation(client_call_details, request)
                code = await call.code()
                if code == grpc.StatusCode.OK:
                    self.status_code_Ok_observed = True

                return call

        interceptor = StatusCodeOkInterceptor()

        async with aio.insecure_channel(self._server_target,
                                        interceptors=[interceptor]) as channel:

            # when no error StatusCode.OK must be observed
            multicallable = channel.unary_unary(
                '/grpc.testing.TestService/UnaryCall',
                request_serializer=messages_pb2.SimpleRequest.SerializeToString,
                response_deserializer=messages_pb2.SimpleResponse.FromString)

            await multicallable(messages_pb2.SimpleRequest())

            self.assertTrue(interceptor.status_code_Ok_observed)
Beispiel #20
0
    async def test_executed_right_order(self):

        interceptors_executed = []

        class Interceptor(aio.UnaryUnaryClientInterceptor):
            """Interceptor used for testing if the interceptor is being called"""

            async def intercept_unary_unary(self, continuation,
                                            client_call_details, request):
                interceptors_executed.append(self)
                call = await continuation(client_call_details, request)
                return call

        interceptors = [Interceptor() for i in range(2)]

        async with aio.insecure_channel(self._server_target,
                                        interceptors=interceptors) as channel:
            multicallable = channel.unary_unary(
                '/grpc.testing.TestService/UnaryCall',
                request_serializer=messages_pb2.SimpleRequest.SerializeToString,
                response_deserializer=messages_pb2.SimpleResponse.FromString)
            call = multicallable(messages_pb2.SimpleRequest())
            response = await call

            # Check that all interceptors were executed, and were executed
            # in the right order.
            self.assertSequenceEqual(interceptors_executed, interceptors)

            self.assertIsInstance(response, messages_pb2.SimpleResponse)
Beispiel #21
0
    async def test_cancel_inside_interceptor_after_rpc_not_awaiting(self):

        class Interceptor(aio.UnaryUnaryClientInterceptor):

            async def intercept_unary_unary(self, continuation,
                                            client_call_details, request):
                call = await continuation(client_call_details, request)
                call.cancel()
                return call

        async with aio.insecure_channel(self._server_target,
                                        interceptors=[Interceptor()
                                                     ]) as channel:

            multicallable = channel.unary_unary(
                '/grpc.testing.TestService/UnaryCall',
                request_serializer=messages_pb2.SimpleRequest.SerializeToString,
                response_deserializer=messages_pb2.SimpleResponse.FromString)
            call = multicallable(messages_pb2.SimpleRequest())

            with self.assertRaises(asyncio.CancelledError):
                await call

            self.assertTrue(call.cancelled())
            self.assertTrue(call.done())
            self.assertEqual(await call.code(), grpc.StatusCode.CANCELLED)
            self.assertEqual(await call.details(),
                             _LOCAL_CANCEL_DETAILS_EXPECTATION)
            self.assertEqual(await call.initial_metadata(), aio.Metadata())
            self.assertEqual(
                await call.trailing_metadata(), aio.Metadata(),
                "When the raw response is None, empty metadata is returned")
Beispiel #22
0
    async def test_call_ok_awaited(self):

        class Interceptor(aio.UnaryUnaryClientInterceptor):

            async def intercept_unary_unary(self, continuation,
                                            client_call_details, request):
                call = await continuation(client_call_details, request)
                await call
                return call

        async with aio.insecure_channel(self._server_target,
                                        interceptors=[Interceptor()
                                                     ]) as channel:

            multicallable = channel.unary_unary(
                '/grpc.testing.TestService/UnaryCall',
                request_serializer=messages_pb2.SimpleRequest.SerializeToString,
                response_deserializer=messages_pb2.SimpleResponse.FromString)
            call = multicallable(messages_pb2.SimpleRequest())
            response = await call

            self.assertTrue(call.done())
            self.assertFalse(call.cancelled())
            self.assertEqual(type(response), messages_pb2.SimpleResponse)
            self.assertEqual(await call.code(), grpc.StatusCode.OK)
            self.assertEqual(await call.details(), '')
            self.assertEqual(await call.initial_metadata(), aio.Metadata())
            self.assertEqual(await call.trailing_metadata(), aio.Metadata())
Beispiel #23
0
    async def test_call_rpc_error_awaited(self):

        class Interceptor(aio.UnaryUnaryClientInterceptor):

            async def intercept_unary_unary(self, continuation,
                                            client_call_details, request):
                call = await continuation(client_call_details, request)
                await call
                return call

        async with aio.insecure_channel(self._server_target,
                                        interceptors=[Interceptor()
                                                     ]) as channel:

            multicallable = channel.unary_unary(
                '/grpc.testing.TestService/UnaryCallWithSleep',
                request_serializer=messages_pb2.SimpleRequest.SerializeToString,
                response_deserializer=messages_pb2.SimpleResponse.FromString)

            call = multicallable(
                messages_pb2.SimpleRequest(),
                timeout=_constants.UNARY_CALL_WITH_SLEEP_VALUE / 2)

            with self.assertRaises(aio.AioRpcError) as exception_context:
                await call

            self.assertTrue(call.done())
            self.assertFalse(call.cancelled())
            self.assertEqual(await call.code(),
                             grpc.StatusCode.DEADLINE_EXCEEDED)
            self.assertEqual(await call.details(), 'Deadline Exceeded')
            self.assertEqual(await call.initial_metadata(), aio.Metadata())
            self.assertEqual(await call.trailing_metadata(), aio.Metadata())
Beispiel #24
0
    async def test_cancel_unary_unary(self):
        async with aio.insecure_channel(self._server_target) as channel:
            hi = channel.unary_unary(
                '/grpc.testing.TestService/UnaryCall',
                request_serializer=messages_pb2.SimpleRequest.
                SerializeToString,
                response_deserializer=messages_pb2.SimpleResponse.FromString)
            call = hi(messages_pb2.SimpleRequest())

            self.assertFalse(call.cancelled())

            # TODO(https://github.com/grpc/grpc/issues/20869) remove sleep.
            # Force the loop to execute the RPC task.
            await asyncio.sleep(0)

            self.assertTrue(call.cancel())
            self.assertFalse(call.cancel())

            with self.assertRaises(
                    asyncio.CancelledError) as exception_context:
                await call

            self.assertTrue(call.cancelled())
            self.assertEqual(await call.code(), grpc.StatusCode.CANCELLED)
            self.assertEqual(await call.details(),
                             'Locally cancelled by application!')
Beispiel #25
0
  def __init__(self, server, config, hist):
    # Create the stub
    if config.HasField('security_params'):
      creds = grpc.ssl_channel_credentials(resources.test_root_certificates())
      channel = test_common.test_secure_channel(
        server, creds, config.security_params.server_host_override)
    else:
      channel = grpc.insecure_channel(server)

    connected_event = threading.Event()
    def wait_for_ready(connectivity):
      if connectivity == grpc.ChannelConnectivity.READY:
        connected_event.set()
    channel.subscribe(wait_for_ready, try_to_connect=True)
    connected_event.wait()

    if config.payload_config.WhichOneof('payload') == 'simple_params':
      self._generic = False
      self._stub = services_pb2.BenchmarkServiceStub(channel)
      payload = messages_pb2.Payload(
          body='\0' * config.payload_config.simple_params.req_size)
      self._request = messages_pb2.SimpleRequest(
          payload=payload,
          response_size=config.payload_config.simple_params.resp_size)
    else:
      self._generic = True
      self._stub = GenericStub(channel)
      self._request = '\0' * config.payload_config.bytebuf_params.req_size

    self._hist = hist
    self._response_callbacks = []
Beispiel #26
0
    async def test_unary_unary(self):
        call = self._stub.UnaryCall(messages_pb2.SimpleRequest())
        validation = inject_callbacks(call)

        self.assertEqual(grpc.StatusCode.OK, await call.code())

        await validation
Beispiel #27
0
    async def test_unary_unary_ok(self):
        call = self._stub.UnaryCall(messages_pb2.SimpleRequest())

        # No exception raised and no message swallowed.
        await call.wait_for_connection()

        response = await call
        self.assertIsInstance(response, messages_pb2.SimpleResponse)
Beispiel #28
0
 async def test_call_code_awaitable(self):
     async with aio.insecure_channel(self._server_target) as channel:
         hi = channel.unary_unary(
             '/grpc.testing.TestService/UnaryCall',
             request_serializer=messages_pb2.SimpleRequest.SerializeToString,
             response_deserializer=messages_pb2.SimpleResponse.FromString)
         call = hi(messages_pb2.SimpleRequest())
         self.assertEqual(await call.code(), grpc.StatusCode.OK)
Beispiel #29
0
 async def coro():
     async with aio.insecure_channel(self.server_target) as channel:
         hi = channel.unary_unary('/grpc.testing.TestService/UnaryCall',
                                  request_serializer=messages_pb2.
                                  SimpleRequest.SerializeToString,
                                  response_deserializer=messages_pb2.
                                  SimpleResponse.FromString)
         await hi(messages_pb2.SimpleRequest())
Beispiel #30
0
def _blocking_unary(stub):
    size = 314159
    request = messages_pb2.SimpleRequest(
        response_type=messages_pb2.COMPRESSABLE,
        response_size=size,
        payload=messages_pb2.Payload(body=b'\x00' * 271828))
    response = stub.UnaryCall(request, timeout=_RPC_TIMEOUT_S)
    _validate_payload_type_and_length(response, messages_pb2.COMPRESSABLE, size)