I would like to use Python unittest to write tests for my GRPC server implementation. I have found grpcio-testing package but I could not find any documentation how to use this.
Let's say that I have the following server:
import helloworld_pb2
import helloworld_pb2_grpc
class Greeter(helloworld_pb2_grpc.GreeterServicer):
def SayHello(self, request, context):
return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name)
How do I create an unit test to call SayHello and check the response?
解决方案
You can start a real server When setUp and stop the server when tearDown.
import unittest
from concurrent import futures
class RPCGreeterServerTest(unittest.TestCase):
server_class = Greeter
port = 50051
def setUp(self):
self.server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
helloworld_pb2_grpc.add_GreeterServicer_to_server(self.server_class(), self.server)
self.server.add_insecure_port(f'[::]:{self.port}')
self.server.start()
def tearDown(self):
self.server.stop(None)
def test_server(self):
with grpc.insecure_channel(f'localhost:{self.port}') as channel:
stub = helloworld_pb2_grpc.GreeterStub(channel)
response = stub.SayHello(helloworld_pb2.HelloRequest(name='Jack'))
self.assertEqual(response.message, 'Hello, Jack!')