| 1 |
# Copyright 2021 The gRPC Authors |
| 2 |
# |
| 3 |
# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
# you may not use this file except in compliance with the License. |
| 5 |
# You may obtain a copy of the License at |
| 6 |
# |
| 7 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
# |
| 9 |
# Unless required by applicable law or agreed to in writing, software |
| 10 |
# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
# See the License for the specific language governing permissions and |
| 13 |
# limitations under the License. |
| 14 |
|
| 15 |
from concurrent import futures |
| 16 |
from typing import Any, Tuple |
| 17 |
|
| 18 |
import gevent |
| 19 |
import grpc |
| 20 |
|
| 21 |
from src.proto.grpc.testing import messages_pb2 |
| 22 |
from src.proto.grpc.testing import test_pb2_grpc |
| 23 |
|
| 24 |
LONG_UNARY_CALL_WITH_SLEEP_VALUE = 1 |
| 25 |
|
| 26 |
|
| 27 |
class TestServiceServicer(test_pb2_grpc.TestServiceServicer): |
| 28 |
|
| 29 |
def UnaryCall(self, request, context): |
| 30 |
return messages_pb2.SimpleResponse() |
| 31 |
|
| 32 |
def UnaryCallWithSleep(self, unused_request, unused_context): |
| 33 |
gevent.sleep(LONG_UNARY_CALL_WITH_SLEEP_VALUE) |
| 34 |
return messages_pb2.SimpleResponse() |
| 35 |
|
| 36 |
|
| 37 |
def start_test_server(port: int = 0) -> Tuple[str, Any]: |
| 38 |
server = grpc.server(futures.ThreadPoolExecutor()) |
| 39 |
servicer = TestServiceServicer() |
| 40 |
test_pb2_grpc.add_TestServiceServicer_to_server(TestServiceServicer(), |
| 41 |
server) |
| 42 |
|
| 43 |
server.add_generic_rpc_handlers((_create_extra_generic_handler(servicer),)) |
| 44 |
port = server.add_insecure_port('[::]:%d' % port) |
| 45 |
server.start() |
| 46 |
return 'localhost:%d' % port, server |
| 47 |
|
| 48 |
|
| 49 |
def _create_extra_generic_handler(servicer: TestServiceServicer) -> Any: |
| 50 |
# Add programatically extra methods not provided by the proto file |
| 51 |
# that are used during the tests |
| 52 |
rpc_method_handlers = { |
| 53 |
'UnaryCallWithSleep': |
| 54 |
grpc.unary_unary_rpc_method_handler( |
| 55 |
servicer.UnaryCallWithSleep, |
| 56 |
request_deserializer=messages_pb2.SimpleRequest.FromString, |
| 57 |
response_serializer=messages_pb2.SimpleResponse. |
| 58 |
SerializeToString) |
| 59 |
} |
| 60 |
return grpc.method_handlers_generic_handler('grpc.testing.TestService', |
| 61 |
rpc_method_handlers) |