Engineer a gRPC contract testing suite with backward compatibility checks, golden…
- User
Engineer a gRPC contract testing suite with backward compatibility checks, golden traces, and fuzzers.
Assistant
Engineer a gRPC contract testing suite with backward compatibility checks, golden traces, and fuzzers.
The user wants a gRPC contract testing suite. This suite needs to include:
Tech Stack Selection:
google.golang.org/grpc, google.golang.org/protobuf.buf is the industry standard for linting and breaking change detection. I should script this or use its library if possible, but command-line invocation is usually easier for a standalone suite.grpcurl or a custom interceptor. A custom interceptor in Go is the most programmable way to "engineer" a suite.testing.F). I can use this combined with the gRPC client to send fuzzed data.Structure of the Solution:
FeatureFlagService).buf (recommended) or a custom Go parser to compare old vs. new descriptor sets.buf or uses the protoparse library to check for field removal, type changes, etc. Actually, for a self-contained engineering example, I'll write a logic block that compares FileDescriptorSets. It's more "engineering" than just "install buf". But buf is the correct answer for production. I will provide a Go script that acts as the orchestrator using buf under the hood or demonstrating the logic of comparing descriptors. Let's go with a custom implementation using protocompare concepts or simply shelling out to buf for reliability. Correction: I'll implement a "Manager" that runs these checks.GoldenRecorder interceptor.GoldenValidator that replays requests against the server and compares responses.testing.F.Detailed Design - Component by Component:
Proto: service.proto defining GetFlag(Request) returns (Response).
Backward Compatibility:
v1 and v2.buf breaking against a stored snapshot, as writing a full proto parser from scratch is too large for a snippet. I will provide the scaffolding for the "Check" function.Golden Traces:
TraceStore.Interceptor: Captures Request/Response pairs.Replayer: Loads traces, hits the server, compares bytes/JSON.Fuzzing:
func FuzzXxx(f *testing.F).Request proto messages.Refining the Output: The user wants "Engineering", implying structure, robustness, and distinct components.
Code specifics:
DescriptorSet binary. This is portable.Let's write the code.
Self-Correction on Backward Compatibility: Writing a full compatibility checker is complex. I will provide a wrapper around protoc or buf concepts, or a simple implementation that checks field numbers. Let's create a lightweight Go implementation that checks if field numbers in the new proto are missing or changed type compared to the old proto.
Self-Correction on Golden Traces: Using any or jsonpb to store the trace.
Drafting the Go Code:
proto/: The definitions.compat/: Logic to load descriptors and compare.golden/: Logic to record/replay.fuzz/: The fuzzer.main.go: The runner.Constraint: The user might expect a single cohesive block of code or a structured project description. I will provide a structured project with file separators.
Step 1: Setup & Proto
A simple Greeter service is too cliché. Let's do a PaymentService.
Step 2: Backward Compatibility
I need to parse .proto files in Go without protoc binary dependency if possible, or assume protoc ran. Assuming protoc ran and generated .pb.go or descriptor.pb is safer.
Actually, the best way is to check the FileDescriptorSet. I will write a utility that compares two FileDescriptorSet binaries.
Step 3: Golden Traces
Interceptor implementation is key here.
func(ctx, req, info, handler)
Save req and resp (if success).
Step 4: Fuzzing
Requires generating random protobuf messages. The protobuf struct tags are hard to fuzz generically without a library. I'll implement a "Smart Proto Fuzzer" helper that uses reflection to populate random values for the specific message type.
Plan:
Let's build it.
Key Challenge: Fuzzing Protobufs dynamically.
dynamicpb or reflection. Since the suite knows the specific service, we can use the generated structs. I will create a helper FuzzMessage(msg proto.Message).Key Challenge: Compatibility checks.
protodesc to compare.Let's write the response.
This is a comprehensive engineering solution for a gRPC Contract Testing Suite. This solution is implemented in Go, leveraging the standard testing package, protobuf libraries, and the buf CLI philosophy for breaking change detection.
The suite consists of three distinct components:
buf CLI (optional, for local checks, but we will implement logic in Go)api.proto)First, define a sample service. We will use this to demonstrate the tests.
// api.proto
syntax = "proto3";
package api;
option go_package = "example.com/api";
service PaymentService {
rpc Process(PaymentRequest) returns (PaymentResponse);
}
message PaymentRequest {
string user_id = 1;
double amount = 2;
// Imagine we add a new field later. Backward compatibility tests check this.
}
message PaymentResponse {
string transaction_id = 1;
bool success = 2;
}
/grpc-suite
/api # Protos
/server # Implementation
/suite
main_test.go # Entry point
compat_test.go # Backward Compatibility
golden_test.go # Golden Traces
fuzzer_test.go # Fuzzing Logic
/testdata
/golden # Stored golden files
/snapshots # Proto descriptors for compat
This component ensures that your API evolution is safe. Instead of just running buf breaking, we will write a Go test that programmatical validates the protobuf descriptor set. This allows you to integrate it into standard CI pipelines without external dependencies.
suite/compat_test.go
package suite
import (
"testing"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/descriptorpb"
"google.golang.org/protobuf/types/known/anypb"
)
// TestBackwardCompatibility loads the current proto descriptor and compares it
// against a "frozen" descriptor from the last release.
func TestBackwardCompatibility(t *testing.T) {
// 1. Load the frozen descriptor set (usually committed to the repo)
// In CI, this file would be downloaded from the 'main' branch artifact.
frozenSet := loadDescriptorSet(t, "testdata/snapshots/v1.0.desc")
// 2. Load the current generated descriptor set
currentSet := loadDescriptorSet(t, "testdata/snapshots/current.desc")
// 3. Run Compatibility Checks
for _, file := range currentSet.GetFile() {
// Find the corresponding file in the frozen set
var oldFile *descriptorpb.FileDescriptorProto
for _, f := range frozenSet.GetFile() {
if f.GetName() == file.GetName() {
oldFile = f
break
}
}
if oldFile == nil {
continue // New file, nothing to break
}
// Check for breaking changes
checkMessageCompatibility(t, oldFile.GetMessageType(), file.GetMessageType())
}
}
func checkMessageCompatibility(t *testing.T, oldMsgs, newMsgs []*descriptorpb.DescriptorProto) {
oldMap := make(map[string]*descriptorpb.DescriptorProto)
for _, m := range oldMsgs {
oldMap[m.GetName()] = m
}
for _, newMsg := range newMsgs {
oldMsg, exists := oldMap[newMsg.GetName()]
if !exists {
continue // New message added
}
// Rule 1: Check Field Deletions
oldFields := make(map[int32]*descriptorpb.FieldDescriptorProto)
for _, f := range oldMsg.GetField() {
oldFields[f.GetNumber()] = f
}
for _, newField := range newMsg.GetField() {
oldField, ok := oldFields[newField.GetNumber()]
if ok {
// Rule 2: Check Type Changes (Simplified check)
if oldField.GetType() != newField.GetType() {
t.Errorf("Breaking Change: Field %s in %s changed type", newField.GetName(), newMsg.GetName())
}
}
}
for num, oldF := range oldFields {
found := false
for _, newF := range newMsg.GetField() {
if newF.GetNumber() == num {
found = true
break
}
}
if !found {
t.Errorf("Breaking Change: Field %d (%s) deleted from %s", num, oldF.GetName(), newMsg.GetName())
}
}
}
}
func loadDescriptorSet(t *testing.T, path string) *descriptorpb.FileDescriptorSet {
// Implementation: Read file and unmarshal into FileDescriptorSet
// Omitted for brevity (standard os.Open / io.ReadAll / proto.Unmarshal)
return &descriptorpb.FileDescriptorSet{}
}
This captures the full context of a request (metadata, payload) and response to ensure the system behavior hasn't drifted unexpectedly. It is superior to snapshot testing because it uses actual binary Protobufs.
suite/golden_test.go
package suite
import (
"context"
"testing"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
"google.golang.org/protobuf/encoding/protojson"
"example.com/api"
"os"
"path/filepath"
)
// TestGoldenTrace replays a recorded request against the server and compares the response
// to the previously recorded "Golden" response.
func TestGoldenTrace(t *testing.T) {
// Setup the server (or connect to a running docker container)
conn := setupGRPCConnection(t)
client := api.NewPaymentServiceClient(conn)
// 1. Load the Golden Scenario
// In a real scenario, we iterate over files in testdata/golden/
scenario := loadGoldenScenario(t, "testdata/golden/payment_success.json")
// 2. Reconstruct Context
ctx := context.Background()
if scenario.Metadata != nil {
ctx = metadata.NewOutgoingContext(ctx, metadata.New(scenario.Metadata))
}
// 3. Execute Request
resp, err := client.Process(ctx, scenario.Request)
if err != nil {
if scenario.ExpectError {
// Compare error message if needed
return
}
t.Fatalf("Request failed unexpectedly: %v", err)
}
// 4. Compare Response (Golden vs Actual)
actualJSON, _ := protojson.Marshal(resp)
expectedJSON, _ := protojson.Marshal(scenario.ExpectedResponse)
if string(actualJSON) != string(expectedJSON) {
t.Errorf("Golden Trace Mismatch!\nExpected: %s\nActual: %s", expectedJSON, actualJSON)
// Optional: Update flag to rewrite goldens
if os.Getenv("UPDATE_GOLDEN") == "true" {
writeGoldenScenario(t, "testdata/golden/payment_success.json", scenario.Request, resp)
}
}
}
// Helper struct to manage scenarios
type GoldenScenario struct {
Metadata map[string]string
Request *api.PaymentRequest
ExpectedResponse *api.PaymentResponse
ExpectError bool
}
func loadGoldenScenario(t *testing.T, path string) *GoldenScenario {
// Load JSON and Unmarshal into struct
// Omitted implementation details
return &GoldenScenario{}
}
Go 1.18+ has native fuzzing support. We will use this to generate random byte sequences and try to unmarshal them into our Protobuf messages, or send them to the server (if we want to test deserialization robustness).
suite/fuzzer_test.go
package suite
import (
"testing"
"google.golang.org/protobuf/proto"
"example.com/api"
)
// FuzzPaymentRequest generates random binary data and attempts to unmarshal it
// into a PaymentRequest. This tests the robustness of the protobuf library
// and any custom validation logic you might have.
func FuzzPaymentRequest(f *testing.F) {
// 1. Seed the fuzzer with valid data (Corpus)
f.Add([]byte("valid_user_id"), float64(100.0))
// You can also add binary representations
validReq := &api.PaymentRequest{UserId: "123", Amount: 50.0}
seedBytes, _ := proto.Marshal(validReq)
f.Add(seedBytes)
// 2. The Fuzz Function
f.Fuzz(func(t *testing.T, data []byte) {
// Attempt to unmarshal random bytes into the struct
req := &api.PaymentRequest{}
if err := proto.Unmarshal(data, req); err != nil {
// If the library rejects it, that's fine (expected behavior)
return
}
// 3. Validation Layer (The actual test)
// If unmarshalling succeeded, ensure our business logic handles
// extreme values (e.g., negative amounts, empty IDs) gracefully.
if req.Amount < 0 {
// Logic check: Should our system accept negative amounts?
// If the fuzzer finds a valid proto that crashes the server,
// we have a bug.
t.Logf("Found valid proto with negative amount: %f", req.Amount)
}
// 4. Server Interaction (Optional - Blackbox Fuzzing)
// If you want to crash the actual server:
// conn := setupGRPCConnection(t)
// client := api.NewPaymentServiceClient(conn)
// _, err := client.Process(context.Background(), req)
// if err != nil { return }
// Check for internal server errors or panics here.
})
}
main_test.go)This ties everything together, allowing you to spin up the server once for the whole suite.
package suite
import (
"net"
"testing"
"google.golang.org/grpc"
"example.com/api"
"google.golang.org/grpc/reflection"
)
// TestMain handles setup and teardown of the gRPC Server for the whole suite
func TestMain(m *testing.M) {
// 1. Start a Dummy gRPC Server in-memory or on a random port
lis, _ := net.Listen("tcp", "localhost:0")
s := grpc.NewServer()
// Register your implementation (Mock or Real DB connection)
api.RegisterPaymentServiceServer(s, &mockPaymentServer{})
reflection.Register(s)
go func() {
s.Serve(lis)
}()
// 2. Run the specific tests (Compat, Golden, Fuzz)
// code := m.Run()
// 3. Teardown
s.GracefulStop()
}
// Helper to get connection
func setupGRPCConnection(t *testing.T) *grpc.ClientConn {
// Logic to connect to the server started in TestMain
// In real life, pass the listener address via context or global var
conn, err := grpc.Dial("localhost:0", grpc.WithInsecure())
if err != nil {
t.Fatal(err)
}
return conn
}
// Mock Implementation
type mockPaymentServer struct {
api.UnimplementedPaymentServiceServer
}
func (s *mockPaymentServer) Process(ctx context.Context, req *api.PaymentRequest) (*api.PaymentResponse, error) {
return &api.PaymentResponse{TransactionId: "txn_123", Success: true}, nil
}
protoc --go_out=. --go-grpc_out=. api/api.protoprotoc -o testdata/snapshots/v1.0.desc api/api.proto to create your baseline.go test ./suite -vgo test ./suite -run=Fuzz -fuzz=FuzzPaymentUPDATE_GOLDEN=true go test ./suite -run TestGoldenTracedescriptorpb to programmatic check for deleted fields or type changes, ensuring API evolution safety.protojson to store human-readable states but binary transmission for requests, allowing precise state validation.