示例#1
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)
示例#2
0
def _server_streaming(stub):
  sizes = (31415, 9, 2653, 58979,)

  request = messages_pb2.StreamingOutputCallRequest(
      response_type=messages_pb2.COMPRESSABLE,
      response_parameters=(
          messages_pb2.ResponseParameters(size=sizes[0]),
          messages_pb2.ResponseParameters(size=sizes[1]),
          messages_pb2.ResponseParameters(size=sizes[2]),
          messages_pb2.ResponseParameters(size=sizes[3]),
      )
  )
  response_iterator = stub.StreamingOutputCall(request)
  for index, response in enumerate(response_iterator):
    _validate_payload_type_and_length(
        response, messages_pb2.COMPRESSABLE, sizes[index])
示例#3
0
    async def test_early_cancel_unary_stream(self):
        """Test cancellation before receiving messages."""
        async with aio.insecure_channel(self._server_target) as channel:
            stub = test_pb2_grpc.TestServiceStub(channel)

            # Prepares the request
            request = messages_pb2.StreamingOutputCallRequest()
            for _ in range(_NUM_STREAM_RESPONSES):
                request.response_parameters.append(
                    messages_pb2.ResponseParameters(
                        size=_RESPONSE_PAYLOAD_SIZE,
                        interval_us=_RESPONSE_INTERVAL_US,
                    ))

            # Invokes the actual RPC
            call = stub.StreamingOutputCall(request)

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

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

            self.assertTrue(call.cancelled())

            self.assertEqual(grpc.StatusCode.CANCELLED,
                             exception_context.exception.code())
            self.assertEqual(_LOCAL_CANCEL_DETAILS_EXPECTATION,
                             exception_context.exception.details())

            self.assertEqual(grpc.StatusCode.CANCELLED, await call.code())
            self.assertEqual(_LOCAL_CANCEL_DETAILS_EXPECTATION, await
                             call.details())
示例#4
0
    async def test_multiple_interceptors_response_iterator(self):
        for interceptor_class in (_UnaryStreamInterceptorEmpty,
                                  _UnaryStreamInterceptorWithResponseIterator):

            with self.subTest(name=interceptor_class):

                interceptors = [interceptor_class(), interceptor_class()]

                channel = aio.insecure_channel(self._server_target,
                                               interceptors=interceptors)
                stub = test_pb2_grpc.TestServiceStub(channel)

                request = messages_pb2.StreamingOutputCallRequest()
                request.response_parameters.extend([
                    messages_pb2.ResponseParameters(
                        size=_RESPONSE_PAYLOAD_SIZE)
                ] * _NUM_STREAM_RESPONSES)

                call = stub.StreamingOutputCall(request)

                response_cnt = 0
                async for response in call:
                    response_cnt += 1
                    self.assertIs(type(response),
                                  messages_pb2.StreamingOutputCallResponse)
                    self.assertEqual(_RESPONSE_PAYLOAD_SIZE,
                                     len(response.payload.body))

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

                await channel.close()
示例#5
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)
示例#6
0
    async def test_response_iterator_using_read(self):
        interceptor = _UnaryStreamInterceptorWithResponseIterator()

        channel = aio.insecure_channel(self._server_target,
                                       interceptors=[interceptor])
        stub = test_pb2_grpc.TestServiceStub(channel)

        request = messages_pb2.StreamingOutputCallRequest()
        request.response_parameters.extend(
            [messages_pb2.ResponseParameters(size=_RESPONSE_PAYLOAD_SIZE)] *
            _NUM_STREAM_RESPONSES)

        call = stub.StreamingOutputCall(request)

        response_cnt = 0
        for response in range(_NUM_STREAM_RESPONSES):
            response = await call.read()
            response_cnt += 1
            self.assertIs(type(response),
                          messages_pb2.StreamingOutputCallResponse)
            self.assertEqual(_RESPONSE_PAYLOAD_SIZE,
                             len(response.payload.body))

        self.assertEqual(response_cnt, _NUM_STREAM_RESPONSES)
        self.assertEqual(interceptor.response_iterator.response_cnt,
                         _NUM_STREAM_RESPONSES)
        self.assertEqual(await call.code(), grpc.StatusCode.OK)

        await channel.close()
示例#7
0
def _ping_pong(stub):
    request_response_sizes = (
        31415,
        9,
        2653,
        58979,
    )
    request_payload_sizes = (
        27182,
        8,
        1828,
        45904,
    )

    with _Pipe() as pipe:
        response_iterator = stub.FullDuplexCall(pipe)
        for response_size, payload_size in zip(request_response_sizes,
                                               request_payload_sizes):
            request = messages_pb2.StreamingOutputCallRequest(
                response_type=messages_pb2.COMPRESSABLE,
                response_parameters=(messages_pb2.ResponseParameters(
                    size=response_size), ),
                payload=messages_pb2.Payload(body=b'\x00' * payload_size))
            pipe.add(request)
            response = next(response_iterator)
            _validate_payload_type_and_length(response,
                                              messages_pb2.COMPRESSABLE,
                                              response_size)
示例#8
0
    async def test_multiple_cancel_unary_stream(self):
        # Prepares the request
        request = messages_pb2.StreamingOutputCallRequest()
        for _ in range(_NUM_STREAM_RESPONSES):
            request.response_parameters.append(
                messages_pb2.ResponseParameters(
                    size=_RESPONSE_PAYLOAD_SIZE,
                    interval_us=_RESPONSE_INTERVAL_US,
                ))

        # Invokes the actual RPC
        call = self._stub.StreamingOutputCall(request)
        self.assertFalse(call.cancelled())

        response = await call.read()
        self.assertIs(type(response), messages_pb2.StreamingOutputCallResponse)
        self.assertEqual(_RESPONSE_PAYLOAD_SIZE, len(response.payload.body))

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

        with self.assertRaises(asyncio.CancelledError):
            await call.read()
示例#9
0
    async def test_cancel_unary_stream_in_task_using_async_for(self):
        coro_started = asyncio.Event()

        # Configs the server method to block forever
        request = messages_pb2.StreamingOutputCallRequest()
        request.response_parameters.append(
            messages_pb2.ResponseParameters(
                size=_RESPONSE_PAYLOAD_SIZE,
                interval_us=_INFINITE_INTERVAL_US,
            ))

        # Invokes the actual RPC
        call = self._stub.StreamingOutputCall(request)

        async def another_coro():
            coro_started.set()
            async for _ in call:
                pass

        task = self.loop.create_task(another_coro())
        await coro_started.wait()

        self.assertFalse(task.done())
        task.cancel()

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

        with self.assertRaises(asyncio.CancelledError):
            await task
示例#10
0
def _cancel_after_first_response(stub):
    request_response_sizes = (31415, 9, 2653, 58979)
    request_payload_sizes = (27182, 8, 1828, 45904)
    with stub, _Pipe() as pipe:
        response_iterator = stub.FullDuplexCall(pipe, _TIMEOUT)

        response_size = request_response_sizes[0]
        payload_size = request_payload_sizes[0]
        request = messages_pb2.StreamingOutputCallRequest(
            response_type=messages_pb2.COMPRESSABLE,
            response_parameters=(messages_pb2.ResponseParameters(
                size=response_size), ),
            payload=messages_pb2.Payload(body=b'\x00' * payload_size))
        pipe.add(request)
        response = next(response_iterator)
        # We test the contents of `response` in the Ping Pong test - don't check
        # them here.
        response_iterator.cancel()

        try:
            next(response_iterator)
        except Exception:
            pass
        else:
            raise ValueError('expected call to be cancelled')
示例#11
0
def _cancel_after_first_response(stub):
    request_response_sizes = (31415, 9, 2653, 58979,)
    request_payload_sizes = (27182, 8, 1828, 45904,)
    with _Pipe() as pipe:
        response_iterator = stub.FullDuplexCall(pipe)

        response_size = request_response_sizes[0]
        payload_size = request_payload_sizes[0]
        request = messages_pb2.StreamingOutputCallRequest(
            response_type=messages_pb2.COMPRESSABLE,
            response_parameters=(
                messages_pb2.ResponseParameters(size=response_size),),
            payload=messages_pb2.Payload(body=b'\x00' * payload_size))
        pipe.add(request)
        response = next(response_iterator)
        # We test the contents of `response` in the Ping Pong test - don't check
        # them here.
        response_iterator.cancel()

        try:
            next(response_iterator)
        except grpc.RpcError as rpc_error:
            if rpc_error.code() is not grpc.StatusCode.CANCELLED:
                raise
        else:
            raise ValueError('expected call to be cancelled')
示例#12
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()))
示例#13
0
    async def test_unary_stream(self):
        channel = aio.insecure_channel(self._server_target)
        stub = test_pb2_grpc.TestServiceStub(channel)

        # Prepares the request
        request = messages_pb2.StreamingOutputCallRequest()
        for _ in range(_NUM_STREAM_RESPONSES):
            request.response_parameters.append(
                messages_pb2.ResponseParameters(size=_RESPONSE_PAYLOAD_SIZE))

        # Invokes the actual RPC
        call = stub.StreamingOutputCall(request)

        # Validates the responses
        response_cnt = 0
        async for response in call:
            response_cnt += 1
            self.assertIs(type(response),
                          messages_pb2.StreamingOutputCallResponse)
            self.assertEqual(_RESPONSE_PAYLOAD_SIZE,
                             len(response.payload.body))

        self.assertEqual(_NUM_STREAM_RESPONSES, response_cnt)
        self.assertEqual(await call.code(), grpc.StatusCode.OK)
        await channel.close()
示例#14
0
def _ping_pong(stub):
    request_response_sizes = (
        31415,
        9,
        2653,
        58979,
    )
    request_payload_sizes = (
        27182,
        8,
        1828,
        45904,
    )

    with _Pipe() as pipe:
        response_iterator = stub.FullDuplexCall(pipe)
        for response_size, payload_size in zip(request_response_sizes,
                                               request_payload_sizes):
            request = messages_pb2.StreamingOutputCallRequest(
                response_type=messages_pb2.COMPRESSABLE,
                response_parameters=(messages_pb2.ResponseParameters(
                    size=response_size), ),
                payload=messages_pb2.Payload(body=b'\x00' * payload_size))
            pipe.add(request)
            response = next(response_iterator)
            if response.payload.type != messages_pb2.COMPRESSABLE:
                raise ValueError('response body of invalid type %s!' %
                                 response.payload.type)
            if len(response.payload.body) != response_size:
                raise ValueError('response body of invalid size %d!' %
                                 len(response.payload.body))
示例#15
0
    async def test_error_in_async_generator(self):
        # Server will pause between responses
        request = messages_pb2.StreamingOutputCallRequest()
        request.response_parameters.append(
            messages_pb2.ResponseParameters(
                size=_RESPONSE_PAYLOAD_SIZE,
                interval_us=_RESPONSE_INTERVAL_US,
            ))

        # We expect the request iterator to receive the exception
        request_iterator_received_the_exception = asyncio.Event()

        async def request_iterator():
            with self.assertRaises(asyncio.CancelledError):
                for _ in range(_NUM_STREAM_RESPONSES):
                    yield request
                    await asyncio.sleep(_SHORT_TIMEOUT_S)
            request_iterator_received_the_exception.set()

        call = self._stub.StreamingInputCall(request_iterator())

        # Cancel the RPC after at least one response
        async def cancel_later():
            await asyncio.sleep(_SHORT_TIMEOUT_S * 2)
            call.cancel()

        cancel_later_task = self.loop.create_task(cancel_later())

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

        await request_iterator_received_the_exception.wait()

        # No failures in the cancel later task!
        await cancel_later_task
示例#16
0
    async def test_cancel_unary_stream(self):
        async with aio.insecure_channel(self._server_target) as channel:
            stub = test_pb2_grpc.TestServiceStub(channel)

            # Prepares the request
            request = messages_pb2.StreamingOutputCallRequest()
            for _ in range(_NUM_STREAM_RESPONSES):
                request.response_parameters.append(
                    messages_pb2.ResponseParameters(
                        size=_RESPONSE_PAYLOAD_SIZE,
                        interval_us=_RESPONSE_INTERVAL_US,
                    ))

            # Invokes the actual RPC
            call = stub.StreamingOutputCall(request)
            self.assertFalse(call.cancelled())

            response = await call.read()
            self.assertIs(type(response),
                          messages_pb2.StreamingOutputCallResponse)
            self.assertEqual(_RESPONSE_PAYLOAD_SIZE,
                             len(response.payload.body))

            self.assertTrue(call.cancel())
            self.assertEqual(grpc.StatusCode.CANCELLED, await call.code())
            self.assertEqual(_LOCAL_CANCEL_DETAILS_EXPECTATION, await
                             call.details())
            self.assertFalse(call.cancel())

            with self.assertRaises(asyncio.CancelledError):
                await call.read()
            self.assertTrue(call.cancelled())
示例#17
0
    async def test_late_cancel_unary_stream(self):
        """Test cancellation after received all messages."""
        async with aio.insecure_channel(self._server_target) as channel:
            stub = test_pb2_grpc.TestServiceStub(channel)

            # Prepares the request
            request = messages_pb2.StreamingOutputCallRequest()
            for _ in range(_NUM_STREAM_RESPONSES):
                request.response_parameters.append(
                    messages_pb2.ResponseParameters(
                        size=_RESPONSE_PAYLOAD_SIZE, ))

            # Invokes the actual RPC
            call = stub.StreamingOutputCall(request)

            for _ in range(_NUM_STREAM_RESPONSES):
                response = await call.read()
                self.assertIs(type(response),
                              messages_pb2.StreamingOutputCallResponse)
                self.assertEqual(_RESPONSE_PAYLOAD_SIZE,
                                 len(response.payload.body))

            # After all messages received, it is possible that the final state
            # is received or on its way. It's basically a data race, so our
            # expectation here is do not crash :)
            call.cancel()
            self.assertIn(await call.code(),
                          [grpc.StatusCode.OK, grpc.StatusCode.CANCELLED])
示例#18
0
async def _ping_pong(stub: test_pb2_grpc.TestServiceStub) -> None:
    request_response_sizes = (
        31415,
        9,
        2653,
        58979,
    )
    request_payload_sizes = (
        27182,
        8,
        1828,
        45904,
    )

    call = stub.FullDuplexCall()
    for response_size, payload_size in zip(request_response_sizes,
                                           request_payload_sizes):
        request = messages_pb2.StreamingOutputCallRequest(
            response_type=messages_pb2.COMPRESSABLE,
            response_parameters=(messages_pb2.ResponseParameters(
                size=response_size), ),
            payload=messages_pb2.Payload(body=b'\x00' * payload_size))

        await call.write(request)
        response = await call.read()
        _validate_payload_type_and_length(response, messages_pb2.COMPRESSABLE,
                                          response_size)
    await call.done_writing()
    await _validate_status_code_and_details(call, grpc.StatusCode.OK, '')
示例#19
0
    async def test_too_many_reads_unary_stream(self):
        """Test cancellation after received all messages."""
        async with aio.insecure_channel(self._server_target) as channel:
            stub = test_pb2_grpc.TestServiceStub(channel)

            # Prepares the request
            request = messages_pb2.StreamingOutputCallRequest()
            for _ in range(_NUM_STREAM_RESPONSES):
                request.response_parameters.append(
                    messages_pb2.ResponseParameters(
                        size=_RESPONSE_PAYLOAD_SIZE, ))

            # Invokes the actual RPC
            call = stub.StreamingOutputCall(request)

            for _ in range(_NUM_STREAM_RESPONSES):
                response = await call.read()
                self.assertIs(type(response),
                              messages_pb2.StreamingOutputCallResponse)
                self.assertEqual(_RESPONSE_PAYLOAD_SIZE,
                                 len(response.payload.body))

            # After the RPC is finished, further reads will lead to exception.
            self.assertEqual(await call.code(), grpc.StatusCode.OK)
            with self.assertRaises(asyncio.InvalidStateError):
                await call.read()
示例#20
0
async def _cancel_after_first_response(stub: test_pb2_grpc.TestServiceStub):
    request_response_sizes = (
        31415,
        9,
        2653,
        58979,
    )
    request_payload_sizes = (
        27182,
        8,
        1828,
        45904,
    )

    call = stub.FullDuplexCall()

    response_size = request_response_sizes[0]
    payload_size = request_payload_sizes[0]
    request = messages_pb2.StreamingOutputCallRequest(
        response_type=messages_pb2.COMPRESSABLE,
        response_parameters=(messages_pb2.ResponseParameters(
            size=response_size), ),
        payload=messages_pb2.Payload(body=b'\x00' * payload_size))

    await call.write(request)
    await call.read()

    call.cancel()

    try:
        await call.read()
    except asyncio.CancelledError:
        assert await call.code() is grpc.StatusCode.CANCELLED
    else:
        raise ValueError('expected call to be cancelled')
示例#21
0
    async def test_early_cancel_unary_stream(self):
        """Test cancellation before receiving messages."""
        # Prepares the request
        request = messages_pb2.StreamingOutputCallRequest()
        for _ in range(_NUM_STREAM_RESPONSES):
            request.response_parameters.append(
                messages_pb2.ResponseParameters(
                    size=_RESPONSE_PAYLOAD_SIZE,
                    interval_us=_RESPONSE_INTERVAL_US,
                ))

        # Invokes the actual RPC
        call = self._stub.StreamingOutputCall(request)

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

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

        self.assertTrue(call.cancelled())

        self.assertEqual(grpc.StatusCode.CANCELLED, await call.code())
        self.assertEqual(_LOCAL_CANCEL_DETAILS_EXPECTATION, await
                         call.details())
示例#22
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()
    try:
        await call.read()
    except aio.AioRpcError as rpc_error:
        assert rpc_error.code() == status
    await _validate_status_code_and_details(call, status, details)
示例#23
0
    async def test_add_done_callback_interceptor_task_finished(self):
        for interceptor_class in (_UnaryStreamInterceptorEmpty,
                                  _UnaryStreamInterceptorWithResponseIterator):

            with self.subTest(name=interceptor_class):
                interceptor = interceptor_class()

                request = messages_pb2.StreamingOutputCallRequest()
                request.response_parameters.extend([
                    messages_pb2.ResponseParameters(
                        size=_RESPONSE_PAYLOAD_SIZE)
                ] * _NUM_STREAM_RESPONSES)

                channel = aio.insecure_channel(self._server_target,
                                               interceptors=[interceptor])
                stub = test_pb2_grpc.TestServiceStub(channel)
                call = stub.StreamingOutputCall(request)

                # This ensures that the callbacks will be registered
                # with the intercepted call rather than saving in the
                # pending state list.
                await call.wait_for_connection()

                validation = inject_callbacks(call)

                async for response in call:
                    pass

                await validation

                await channel.close()
示例#24
0
    async def test_multiple_cancel_unary_stream(self):
        async with aio.insecure_channel(self._server_target) as channel:
            stub = test_pb2_grpc.TestServiceStub(channel)

            # Prepares the request
            request = messages_pb2.StreamingOutputCallRequest()
            for _ in range(_NUM_STREAM_RESPONSES):
                request.response_parameters.append(
                    messages_pb2.ResponseParameters(
                        size=_RESPONSE_PAYLOAD_SIZE,
                        interval_us=_RESPONSE_INTERVAL_US,
                    ))

            # Invokes the actual RPC
            call = stub.StreamingOutputCall(request)
            self.assertFalse(call.cancelled())

            response = await call.read()
            self.assertIs(type(response),
                          messages_pb2.StreamingOutputCallResponse)
            self.assertEqual(_RESPONSE_PAYLOAD_SIZE,
                             len(response.payload.body))

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

            with self.assertRaises(grpc.RpcError) as exception_context:
                await call.read()
示例#25
0
def _server_streaming(stub):
    sizes = (31415, 9, 2653, 58979)

    with stub:
        request = messages_pb2.StreamingOutputCallRequest(
            response_type=messages_pb2.COMPRESSABLE,
            response_parameters=(
                messages_pb2.ResponseParameters(size=sizes[0]),
                messages_pb2.ResponseParameters(size=sizes[1]),
                messages_pb2.ResponseParameters(size=sizes[2]),
                messages_pb2.ResponseParameters(size=sizes[3]),
            ))
        response_iterator = stub.StreamingOutputCall(request, _TIMEOUT)
        for index, response in enumerate(response_iterator):
            if response.payload.type != messages_pb2.COMPRESSABLE:
                raise ValueError('response body of invalid type %s!' %
                                 response.payload.type)
            if len(response.payload.body) != sizes[index]:
                raise ValueError('response body of invalid size %d!' %
                                 len(response.payload.body))
示例#26
0
async def _server_streaming(stub: test_pb2_grpc.TestServiceStub) -> None:
    sizes = (
        31415,
        9,
        2653,
        58979,
    )

    request = messages_pb2.StreamingOutputCallRequest(
        response_type=messages_pb2.COMPRESSABLE,
        response_parameters=(
            messages_pb2.ResponseParameters(size=sizes[0]),
            messages_pb2.ResponseParameters(size=sizes[1]),
            messages_pb2.ResponseParameters(size=sizes[2]),
            messages_pb2.ResponseParameters(size=sizes[3]),
        ))
    call = stub.StreamingOutputCall(request)
    for size in sizes:
        response = await call.read()
        _validate_payload_type_and_length(response, messages_pb2.COMPRESSABLE,
                                          size)
示例#27
0
async def _perform_unary_stream(stub, wait_for_ready):
    request = messages_pb2.StreamingOutputCallRequest()
    for _ in range(_NUM_STREAM_RESPONSES):
        request.response_parameters.append(
            messages_pb2.ResponseParameters(size=_RESPONSE_PAYLOAD_SIZE))

    call = stub.StreamingOutputCall(request,
                                    timeout=test_constants.LONG_TIMEOUT,
                                    wait_for_ready=wait_for_ready)

    for _ in range(_NUM_STREAM_RESPONSES):
        await call.read()
    assert await call.code() == grpc.StatusCode.OK
示例#28
0
    async def test_max_message_length_applied(self):
        address, server = await start_test_server()

        async with aio.insecure_channel(
                address,
                options=((_GRPC_ARG_MAX_RECEIVE_MESSAGE_LENGTH,
                          _MAX_MESSAGE_LENGTH), )) as channel:
            stub = test_pb2_grpc.TestServiceStub(channel)

            request = messages_pb2.StreamingOutputCallRequest()
            # First request will pass
            request.response_parameters.append(
                messages_pb2.ResponseParameters(size=_MAX_MESSAGE_LENGTH //
                                                2, ))
            # Second request should fail
            request.response_parameters.append(
                messages_pb2.ResponseParameters(size=_MAX_MESSAGE_LENGTH *
                                                2, ))

            call = stub.StreamingOutputCall(request)

            response = await call.read()
            self.assertEqual(_MAX_MESSAGE_LENGTH // 2,
                             len(response.payload.body))

            with self.assertRaises(aio.AioRpcError) as exception_context:
                await call.read()
            rpc_error = exception_context.exception
            self.assertEqual(grpc.StatusCode.RESOURCE_EXHAUSTED,
                             rpc_error.code())
            self.assertIn(str(_MAX_MESSAGE_LENGTH), rpc_error.details())

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

        await server.stop(None)
示例#29
0
async def _perform_stream_stream(stub, wait_for_ready):
    call = stub.FullDuplexCall(timeout=test_constants.LONG_TIMEOUT,
                               wait_for_ready=wait_for_ready)

    request = messages_pb2.StreamingOutputCallRequest()
    request.response_parameters.append(
        messages_pb2.ResponseParameters(size=_RESPONSE_PAYLOAD_SIZE))

    for _ in range(_NUM_STREAM_RESPONSES):
        await call.write(request)
        response = await call.read()
        assert _RESPONSE_PAYLOAD_SIZE == len(response.payload.body)

    await call.done_writing()
    assert await call.code() == grpc.StatusCode.OK
    async def test_intercepts(self):

        for interceptor_class in (
                _StreamStreamInterceptorEmpty,
                _StreamStreamInterceptorWithRequestAndResponseIterator):

            with self.subTest(name=interceptor_class):
                interceptor = interceptor_class()
                channel = aio.insecure_channel(self._server_target,
                                               interceptors=[interceptor])
                stub = test_pb2_grpc.TestServiceStub(channel)

                # Prepares the request
                request = messages_pb2.StreamingOutputCallRequest()
                request.response_parameters.append(
                    messages_pb2.ResponseParameters(
                        size=_RESPONSE_PAYLOAD_SIZE))

                async def request_iterator():
                    for _ in range(_NUM_STREAM_REQUESTS):
                        yield request

                call = stub.FullDuplexCall(request_iterator())

                await call.wait_for_connection()

                response_cnt = 0
                async for response in call:
                    response_cnt += 1
                    self.assertIsInstance(
                        response, messages_pb2.StreamingOutputCallResponse)
                    self.assertEqual(_RESPONSE_PAYLOAD_SIZE,
                                     len(response.payload.body))

                self.assertEqual(response_cnt, _NUM_STREAM_RESPONSES)
                self.assertEqual(await call.code(), grpc.StatusCode.OK)
                self.assertEqual(await call.initial_metadata(), aio.Metadata())
                self.assertEqual(await call.trailing_metadata(),
                                 aio.Metadata())
                self.assertEqual(await call.details(), '')
                self.assertEqual(await call.debug_error_string(), '')
                self.assertEqual(call.cancel(), False)
                self.assertEqual(call.cancelled(), False)
                self.assertEqual(call.done(), True)

                interceptor.assert_in_final_state(self)

                await channel.close()