tonic-mock
tonic is a great crate to build GRPC applications. However, testing RPC built with tonic is not straightforward, especially for the streaming interface. If you have an RPC like this:
rpc Push(stream RequestPush) returns (stream ResponsePush);
Testing it usually involves lots of effort on properly mocking the data. This little crate helps to make it easier to mock the incoming data and to manipulate the response so that you could focus on testing the logic itself. For example:
async
Features
Core Functionality
Seven main functions provided:
streaming_request: build streaming requests based on a vector of messages.streaming_request_with_interceptor: build streaming requests with an interceptor function.request_with_interceptor: create a standard (non-streaming) request with an interceptor.process_streaming_response: iterate the streaming response and call the closure user provided.process_streaming_response_with_timeout: iterate the streaming response with a timeout for each message.stream_to_vec: iterate the streaming response and generate a vector for further processing.stream_to_vec_with_timeout: iterate the streaming response with a timeout and generate a vector.
Bidirectional Streaming Testing
The crate provides a BidirectionalStreamingTest utility for fine-grained testing of bidirectional streaming services:
use Duration;
use Runtime;
use ;
// Create a runtime
let rt = new.unwrap;
rt.block_on;
Key features of BidirectionalStreamingTest:
- Send messages one by one to the service
- Receive and test responses individually
- Support for timeouts when receiving responses
- More control over message flow compared to using a pre-collected vector
For a complete example, see examples/bidirectional_streaming_test_api.rs.
Request Interceptors
The crate provides support for request interceptors, which allow you to modify requests before they are sent. This is useful for adding metadata, headers, or performing other customizations:
use MetadataValue;
use streaming_request_with_interceptor;
// Create a streaming request with an interceptor that adds headers
let request = streaming_request_with_interceptor;
// For non-streaming requests
let request = request_with_interceptor;
Timeout Support
The crate provides functions for handling timeouts in streaming responses:
// Process streaming response with a 1-second timeout for each message
process_streaming_response_with_timeout.await;
// Convert stream to vector with timeout
let results = stream_to_vec_with_timeout.await;
for result in results
Test Utilities
The crate also provides optional test utilities to help with testing gRPC services. Enable these with the test-utils feature (enabled by default):
[]
= "0.4" # Test utilities are included by default
# If you want to disable test utilities
= { = "0.4", = false }
Test utilities include:
TestRequestandTestResponsetypes: Simple message types for testingcreate_test_messages: Generate test messages with sequential IDscreate_stream_response: Create a streaming response from a vector of messagescreate_stream_response_with_errors: Create a streaming response with errors at specified indicesassert_message_eq: Assert that a message matches expected valuesassert_response_eq: Assert that a response matches expected values
Example using test utilities:
use ;
use ;
async
For a more complete example, check the examples/grpc_test_demo.rs file which demonstrates:
- Testing client streaming RPC (client sends multiple messages, server sends one response)
- Testing server streaming RPC (client sends one message, server sends multiple responses)
- Testing bidirectional streaming RPC (client and server both send multiple messages)
- Testing error handling in streaming RPCs
- Testing timeouts in streaming responses
- Using request interceptors to modify requests
Note these functions are for testing purpose only. DO NOT use them in other cases.
gRPC Mock Utilities
The crate provides utilities for low-level mocking of gRPC messages:
use ;
use ;
use Status;
// Encode a gRPC request
let request = new;
let encoded = encode_grpc_request;
// Decode a gRPC message
let decoded: TestRequest = decode_grpc_message.unwrap;
assert_eq!;
// Mock a gRPC call with a handler function
let response = mock_grpc_call.unwrap;
These utilities give you fine-grained control over gRPC message encoding/decoding, which is useful for:
- Testing gRPC handlers directly without setting up a full service
- Implementing custom gRPC client/server logic
- Debugging gRPC message format issues
- Testing custom error handling in gRPC services
For a complete example, see examples/grpc_mock_example.rs.
Mockable gRPC Client
The crate provides a MockableGrpcClient utility for mocking gRPC clients:
use ;
use ;
// Define a client type that will use the mock
// Implement the GrpcClientExt trait for your client
// Create a mock client and configure mock responses
async
Here's a more complete example with proper error handling:
use ;
use ;
use Message;
use Error;
// Define message types
// Define a client that will use the mock
// Implement the extension trait
// Implement client methods
async
Key features of the mockable client:
- Configure responses for specific service methods
- Return different responses based on request content with predicates
- Simulate error responses
- Include custom metadata in responses
- Add delays to simulate network latency
- Reset mock configurations between tests
For a complete example, see examples/mockable_client_example.rs.
License
tonic-mock is distributed under the terms of MIT.
See LICENSE for details.
Copyright 2021 Tyr Chen