March 1, 2024

Automatic code-first gRPC schema validation with unit tests

 Code-first gRPC uses .NET types to define service and message contracts and is a very convenient choice when your entire ecosystem uses .NET. Instead of the schema being persisted in a .proto file, the schema is defined in the .NET types. This is a great way to define the schema as it allows for easy updates and refactoring via C# tooling.

However, when refactoring code or modifying gRPC models it can also be difficult to guarantee that the schema is still backwards compatible. This is because the schema is defined in the .NET types and not in a .proto file. It is not always obvious if the schema has changed in a way that is not backwards compatible.

Furthermore, unit tests will also be using the latest code-first models. As a result the tests will pass even if you rename a field or change a type in a way that is not backwards compatible with existing clients. This can lead to breaking changes being merged and deployed without anyone realising the impact until clients start failing in production.

Proto schema generation to the rescue

This project was largely driven by FDD (Fear Driven Development). I was working on large gRPC middleware application that was the interface to a number of mainframe COBOL programs. Some of these programs could not reliably be tested via integration tests as they were destructive procedures. I was discussing the potential of unintended model changes with my colleague Brad and we devised a way to detect unintended gRPC schema changes using gRPC reflection. A handy feature of gRPC schema generation is that it can generate a .proto file directly from your .NET types.

Integrating Proto Schema change detection into your continuous build process

This package has been built to integrate proto schema checks directly into a build pipeline. By adding one test to generate baseline .proto files and another to verify schema stability on every build, a CI pipeline will fail fast whenever contract drift is introduced. That gives reviewers immediate visibility of schema diffs and helps catch potentially breaking API changes before they are merged or deployed.

The code is on GitHub:  andyvans/GrpcCodeFirstContractGuard

Package

Package Description
Codify.GrpcCodeFirstContractGuard Generates and validates .proto schemas from code-first gRPC service interfaces

Getting started

Install the package in your test project:

dotnet add package Codify.GrpcCodeFirstContractGuard

The package exposes two methods:

  • ProtoContractGuard.GenerateResourceFiles — generates baseline .proto schema files from your code-first service interfaces and writes them to disk.
  • ProtoContractGuard.VerifyProtobufSchemaStable — regenerates schemas in memory and compares them against the persisted baselines, returning any differences.

Usage

Here is a complete xUnit example with both tests:

using Codify.GrpcCodeFirstContractGuard;
using FluentAssertions;

public class ProtoSchemaTests
{
    /// <summary>
    /// Generates baseline .proto files into the ProtoContractGuard folder.
    /// Run manually when adding new services or after intentional schema changes.
    /// Commit the generated files to source control.
    /// </summary>
    [Fact(Skip = "Run manually to regenerate baseline")]
    public void GenerateProtoSchema()
    {
        var generatedFiles = ProtoContractGuard.GenerateResourceFiles(
        [
            typeof(IGreeterCodeFirst)
        ]);

        generatedFiles.Should().HaveCount(1);
    }

    /// <summary>
    /// Runs on every build. Fails if the current schema differs from the baseline.
    /// </summary>
    [Fact]
    public void VerifyProtobufSchema_Stable()
    {
        var schemaDifferences = ProtoContractGuard.VerifyProtobufSchemaStable(
        [
            typeof(IGreeterCodeFirst)
        ]);

        schemaDifferences.Should().BeEmpty(
            "Schema differences should be empty for stable protobuf schemas");
    }
}

When a schema change is detected the verification test will fail with line-level output showing exactly what changed:

ProtoContractGuard IGreeterCodeFirst differences:
  -    string FirstName = 1;
 6+    string Name = 1;
  -    string Infomation = 1;
 8+    string Info = 1;
  -    rpc SayHowdy (HelloCodeFirstRequest) returns (HelloCodeFirstResponse);
22+    rpc SayHello (HelloCodeFirstRequest) returns (HelloCodeFirstResponse);

If a schema change is intentional, rerun GenerateResourceFiles to update the baseline and commit the new .proto files alongside your code change.

How it works

Internally, the package does three things:

  1. Finds your service interfaces by namespace and [ServiceContract].
  2. Generates current .proto schemas with protobuf-net.Grpc.Reflection.
  3. Compares baseline vs generated schema using DiffPlex inline diff.

Service discovery is done via assembly scanning:

private static IEnumerable<Type> GetGrpcServiceInterfaces(
    IEnumerable<Type> grpcContractTypes,
    IEnumerable<Assembly>? grpcAssemblies)
{
    var contractNamespaces = new HashSet<string>(grpcContractTypes
        .Select(t => t.Namespace)
        .Where(ns => ns != null)!);

    grpcAssemblies ??= AppDomain.CurrentDomain.GetAssemblies();

    return grpcAssemblies
        .SelectMany(assembly => assembly.GetTypes())
        .Where(type => type.Namespace != null && contractNamespaces.Contains(type.Namespace))
        .Where(type => type.IsInterface && type.GetCustomAttribute<ServiceContractAttribute>() != null);
}

Schema diffs are generated and normalized into readable lines:

var diff = InlineDiffBuilder.Diff(currentSchema, newSchema);

var differences = diff.Lines
    .Where(diffPiece => diffPiece.Type != ChangeType.Unchanged)
    .Select(diffLine => new
    {
        ChangeType = diffLine.Type switch
        {
            ChangeType.Deleted => "-",
            ChangeType.Inserted => "+",
            ChangeType.Modified => "!",
            _ => "?"
        },
        Position = diffLine.Position
    })
    .ToList();

Baseline files are written relative to the test file (via [CallerFilePath]) into a ProtoContractGuard folder by default, which makes the baseline location deterministic and source-control friendly.

Final notes

A failing schema test does not always mean a breaking change, but it is a strong signal to stop and review before merging. If the change is intentional, regenerate the baseline and commit the updated .proto files alongside the contract change.