Search code examples
pythongrpcgrpc-python

How to Test ServiceInterceptor using grpcio-testing in Python


I have a proto file like

syntax = "proto3";

package hello;

message HelloRequest {
}

message HelloResponse {
}

service HelloService {
    rpc UnaryUnaryHello (HelloRequest) returns (HelloResponse) {}
    rpc UnaryStreamHello (HelloRequest) returns (stream HelloResponse) {}
    rpc StreamUnaryHello (stream HelloRequest) returns (HelloResponse) {}
    rpc StreamStreamHello (stream HelloRequest) returns (stream HelloResponse) {}
}

And then I've generated the base servicer and stubs for it.

I also created a server interceptor for it, MyServerInterceptor.

Now I am trying to test the interceptor using grpcio-testing, but can't figure it out. I am actually having trouble finding any documentation on how to use the library, which looks like a known issue.

From that issue, I found this example, however I can't figure out how to add interceptors to the test server.

Also, the way the tests use the lower level DESCRIPTORS seems rather clunky. Is there a way to use the generated stubs to make the requests?

Finally, the example shows passing a dict {} as invocation_metadata, but I thought invocation_metadata was supposed to be a list of tuples List[Tuple[str,str]]?


Solution

  • The example you posted is not merged yet. I would recommend to test the gRPC service in Python with actual gRPC client/server instead of the mocking library. In this way, you are testing the server logic in the way that a client would.

    And you are right about the metadata type, it should be List[Tuple[str, str].