I've described how to bootstrap a simple grpc server in python,now it's time to test the grpc service.
I'm using pytest-grpc to write unit test for grpc service. pytest-grpc is a pytest plugin, it's leverage the power of pytest fixtures to make unit test for grpc service very easy. to write unit test for grpc, there are 3 specific pytest fixtures to implement, it's recommended to import artifacts within the fixture method to avoid package confilict
- grpc_add_to_server
the test need to know how to add grpc servicer into grpc server, this fixutre will return the generated funciton to add grpc servicer to grpc server
@pytest.fixture(scope='module')
def grpc_add_to_server():
from grpc_mate.helloworld_pb2_grpc import add_GreeterServicer_to_server
return add_GreeterServicer_to_server
- grpc_servicer
the test need to know what servicer instance need to add to grpc server, this fixture methjod should return a servicer instnace
@pytest.fixture(scope='module')
def grpc_servicer():
from service.greeter_servicer import GreeterServicer
return GreeterServicer()
- grpc_stub_cls
the test need to know which client stub class to use to init the grpc stub instance
@pytest.fixture(scope='module')
def grpc_stub_cls(grpc_channel):
from grpc_mate.helloworld_pb2_grpc import GreeterStub
return GreeterStub
after we provide these information, pytest-grpc will do the rest for us, it will take care of the grpc server/ channel's creation and termination, it will help us to construct the client stub, what we need to do is just focus on write meaningful unit test to test out grpc logic, like below
def test_SayHello(grpc_stub):
hello_request = HelloRequest(name='ivan')
response = grpc_stub.SayHello(hello_request)
assert response.message == f'hello {hello_request.name}'
see the full example from test_greeter_servicer.py
grpc-python do have it's own module to test grpc server, but I find the api is very confusing and the test code is not easy to maintain, so it's not recommended to use grpc-python's offical test module.