GripMock Documentation

repository·master·Indexed 20 days ago

https://github.com/tokopedia/gripmock

GripMock is a mock server for gRPC services that generates server implementations from .proto files. It enables end-to-end testing and software development by allowing developers to define request expectations and responses via a REST API or static JSON files. It includes a gRPC server for handling RPC calls and a Stub server for managing mock mappings, supporting matching rules such as equals, contains, and regular expressions.

Tokens
2.3K
Snippets
5
Records
12
Agent score
71%

What's inside GripMock

  1. Input Headers Matching Rule

    master

    You can match incoming gRPC metadata/headers by specifying a headers field inside the input object. Headers are treated as a map of strings, and you can use the same four rules: equals, equals_unordered, contains, and matches.

    Important: Only one rule type is applied to headers at a time. If multiple rule types are provided in the headers object, only the first matching rule will be used.

    {
      "service": "YourService",
      "method": "YourMethod",
      "input": {
        "equals": {
          "field1": "value1"
        },
        "headers": {
          "equals": {
            "Content-Type": "application/json"
          }
        }
      },
      "output": {
        "data": {
          "result": "success"
        }
      }
    }
  2. Input Matching Rules

    master

    GripMock supports four primary rules for matching gRPC request payloads. These rules support nested fields for all JSON data types (string, bool, array, etc.).

    • equals: Matches the exact field name and value.
    • equals_unordered: Matches exact field names and values, but treats lists/arrays as sets (order does not matter).
    • contains: Matches if the input contains the declared expected fields (useful for partial matching).
    • matches: Uses regular expressions to match field values. Supports strings and arrays of strings.
  3. How GripMock works

    master

    GripMock operates using two main components that work in tandem:

    1. gRPC Server (tcp://localhost:4770): Receives incoming RPC calls from clients, parses the input, and queries the Stub server to find a matching stub.
    2. Stub Server (http://localhost:4771): A REST API that manages stub mappings. It allows you to add, list, clear, or reset stubs via HTTP requests.

    Technically, GripMock uses a protoc plugin (protoc-gen-gripmock) to translate protobuf declarations into a Go-based gRPC server implementation.

  4. Quick Start with GripMock using Docker

    master

    To quickly set up a mock server, use the tkpd/gripmock Docker image. You must provide a .proto file to generate the gRPC service implementation.

    1. Pull the image: docker pull tkpd/gripmock
    2. Run the container: Mount your local directory containing the .proto file to /proto inside the container and expose the necessary ports (default 4770 for gRPC and 4771 for the Stub HTTP service).
    3. Add a stub: Use curl to send a JSON payload to the Stub service's /add endpoint.
    4. Test: Run your gRPC client against localhost:4770.
    # 1. Pull image
    docker pull tkpd/gripmock
    
    # 2. Run container (replace /mypath with your actual path)
    docker run -p 4770:4770 -p 4771:4771 -v /mypath:/proto tkpd/gripmock /proto/hello.proto
    
    # 3. Add a stub via HTTP
    curl -X POST -d '{"service":"Gripmock","method":"SayHello","input":{"equals":{"name":"gripmock"}},"output":{"data":{"message":"Hello GripMock"}}}' localhost:4771/add
  5. Static Stubbing via --stub flag

    master

    Instead of adding stubs dynamically, you can initialize GripMock with a set of predefined stub JSON files. Use the --stub argument to provide the directory path where these files are located.

    Example using Docker: docker run -p 4770:4770 -p 4771:4771 -v /mypath:/proto -v /mystubs:/stub tkpd/gripmock --stub=/stub /proto/hello.proto

    Note: Even with static stubs loaded, the HTTP Stub API remains available to modify mappings at runtime.

    docker run -p 4770:4770 -p 4771:4771 -v /mypath:/proto -v /mystubs:/stub tkpd/gripmock --stub=/stub /proto/hello.proto
  6. Understand GripMock gRPC method types

    master

    The generator identifies and categorizes gRPC methods into four distinct types based on their streaming capabilities. This classification is used to generate the appropriate server implementation:

    • standard: Unary RPC (one request, one response).
    • server-stream: Server-to-client streaming (one request, multiple responses).
    • client-stream: Client-to-server streaming (multiple requests, one response).
    • bidirectional: Bidirectional streaming (multiple requests, multiple responses).
  7. Configure protoc-gen-gripmock via command-line parameters

    master

    The protoc-gen-gripmock plugin accepts configuration parameters passed through the protoc command line using the --gripmock_out (or similar) flag. These parameters are parsed as comma-separated key=value pairs.

    Supported parameters include:

    • admin-port: The port used for the GripMock admin interface.
    • grpc-address: The host address for the gRPC server.
    • grpc-port: The port for the gRPC server.
    • pbPath: (Internal use) Path to protobuf definitions.

    Example of passing these via protoc:

    protoc --gripmock_out=. --gripmock_opt=admin-port=8080,grpc-address=0.0.0.0,grpc-port=9090 your_service.proto
  8. Run the GripMock CLI

    master

    GripMock is a CLI tool that generates a gRPC mock server from .proto files. It starts an admin server for managing stubs and a gRPC server to handle mock requests.

    To use GripMock, you must provide at least one .proto file as a positional argument. The tool requires the GOPATH environment variable to be set, as it uses it to determine the output directory for generated code.

    Usage Pattern: gripmock [flags] <proto_file_1> <proto_file_2> ...

    gripmock -grpc-port 4770 -admin-port 4771 path/to/your/service.proto
  9. Dynamic Stubbing via REST API

    master

    The Stub server (running on port :4771) allows you to manage mock behaviors on the fly using a REST API.

    Endpoints:

    • GET /: List all current stub mappings.
    • POST /add: Add a new stub using the JSON stub format.
    • POST /find: Find a matching stub for a specific input. Use the format {"service":"<name>", "method":"<name>", "data":{...}}.
    • GET /clear: Clear all existing stub mappings.
    • POST /reset: Clear all stubs and reload them from the configured stub file path (if provided via --stub).
    • GET /requests: List all recorded requests made to the stub server.
  10. Stub JSON Format

    master

    Stubs are defined using JSON. A stub maps a specific gRPC service and method to an input matching rule and an output response.

    Schema:

    • service: The name of the service defined in the .proto file.
    • method: The name of the gRPC method to mock.
    • input: An object containing the matching rule (e.g., equals, contains).
    • output: The response to return if the input matches.
      • data: The JSON object representing the response payload.
      • headers: (Optional) Response headers.
      • error: (Optional) Error message to return.
      • code: (Optional) gRPC response code. If code != 0, an error is returned instead of data.
    {
      "service":"<servicename",
      "method":"<methodname>",
      "input":{
        // input matching rule
      },
      "output":{
        "data":{
          // result fields
        },
        "headers": {
          // result headers
        },
        "error":"<error message>",
        "code":"<response code>"
      }
    }
  11. Requirements for proto files used with protoc-gen-gripmock

    master

    To successfully generate a GripMock server, your .proto files must satisfy the following requirements:

    1. go_package option: Every proto file must define a go_package option. The generator uses this to resolve Go package aliases and dependencies.
    2. Package Aliasing: The generator supports the go_package alias syntax (package_name;alias_name). If an alias is not provided, the generator attempts to derive one from the folder name (replacing - with _).
    3. Keyword Safety: If a derived package alias matches a Go keyword (e.g., type, func, map), the generator automatically appends _pb to the alias to ensure valid Go code generation.
  12. GripMock CLI Flags Reference

    master

    The following flags are available for configuring the GripMock server behavior:

    FlagDefaultDescription
    -o$GOPATH/src/grpcDirectory to output the generated server.go
    -grpc-port4770Port of the gRPC TCP server
    -grpc-listenlocalhostAddress the gRPC server will bind to (use 0.0.0.0 for external access)
    -admin-port4771Port of the stub admin server
    -admin-listenlocalhostAddress the admin server will bind to (use 0.0.0.0 for external access)
    -stub(empty)Path where the stub files are located (Optional)
    -imports/protobufComma-separated import paths. Default /protobuf is used by the GripMock Dockerfile to install WKT (Well-Known Type) protos.