我采纳了J.C的想法并将其扩展为能够为每个测试用例创建一个假服务器(mock)。另外,在端口0上绑定以避免端口冲突:@contextmanager
def helloworld(cls):
"""Instantiate a helloworld server and return a stub for use in tests"""
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
helloworld_pb2_grpc.add_GreeterServicer_to_server(cls(), server)
port = server.add_insecure_port('[::]:0')
server.start()
try:
with grpc.insecure_channel('localhost:%d' % port) as channel:
yield helloworld_pb2_grpc.GreeterStub(channel)
finally:
server.stop(None)
class HelloWorldTest(unittest.TestCase):
def test_hello_name(self):
# may do something extra for this mock if it's stateful
class FakeHelloworld(helloworld_pb2_grpc.GreeterServicer):
def SayHello(self, request, context):
return helloworld_pb2.SayHelloResponse()
with helloworld(Fakehelloworld) as stub:
response = stub.SayHello(helloworld_pb2.HelloRequest(name='Jack'))
self.assertEqual(response.message, 'Hello, Jack!')