gRPC
mockgrpc runs gRPC mock servers for tests, and for the vlatte command.
A gRPC mock server serves any method of the services whose generated code the program imports: it needs no implementation registered. A mock names its method, matches the calls, and answers them, whatever their type: unary, server streaming, client streaming or bidi streaming.
func TestGreeter(t *testing.T) {
m := mockgrpc.MustNew(mockgrpc.Setup().InMemory()) // no port: only m.Dial reaches it
m.MustStart()
t.Cleanup(m.Close)
m.MustMock(mockgrpc.Method("greeter.Greeter/SayHello").
Header("x-team", match.Equal("core")).
Field("name", match.Equal("ann")).
Reply(mockgrpc.Message(&pb.HelloReply{Message: "hi ann"})))
client := pb.NewGreeterClient(m.MustDial()) // closed with the server
res, err := client.SayHello(metadata.AppendToOutgoingContext(t.Context(), "x-team", "core"), &pb.HelloRequest{Name: "ann"})
// ...
}Setup().InMemory() serves on an in-memory listener, with no port: only m.Dial() reaches it. Without it, the server listens on a local port, which m.Addr() names, for clients of any language.
Mock features
As HTTP mocks, gRPC mocks have an ID, a Name and a Priority, can start Enabled(false), serve a number of calls with Times and Once, take part in scenarios with StartScenario, ScenarioIs, ScenarioStateIs, ScenarioStateWillBe and ScenarioKey, wait before replying with Delay and DelayFunc, and run on_complete events, such as webhooks, with OnCompleteEvent, and callbacks with Callback. An answer with a status counts as the mock's answer, for Times too. A scenario moves when its mock is picked to answer, before it answers.
See Mock lifecycle, Scenarios and Webhooks and events.
The server
A gRPC server keeps a journal of its calls with Setup().Journal(dir), which tests verify as HTTP tests do, serves an admin API with Setup().Admin(admin.MustNew()), whose mocks Setup().AdminStore(mockgrpc.FileStore(dir)) keeps across restarts, and answers a call no mock matched with Setup().NoMatchCode(code), NotFound by default. Setup().ServerOptions(...) passes options to the grpc.Server, such as interceptors.
In this section
- Methods: naming the method a mock answers.
- Request matching: metadata, fields and messages.
- Replies: messages, statuses, sequences and functions.
- Streaming: server, client and bidi streams.
- Cuts: a server that dies midway.
- Descriptors and reflection: serving services without their generated code.
- Proxying: answers of another gRPC server. Recording has a section of its own.
- Mock files: the YAML and JSON format.
- TLS.
- Troubleshooting: no-match codes, trailers and debug metadata.
What gRPC shares with HTTP, such as matchers, scenarios, templates, webhooks and the journal, works the same for both: each has a section of its own in the sidebar.