### Run GripMock with E-commerce Example Source: https://github.com/bavix/gripmock/blob/master/examples/projects/ecommerce/README.md Start GripMock with the e-commerce service definition and stub directory. This command initializes the mock server with the specified configurations. ```bash go run main.go examples/projects/ecommerce/service.proto --stub examples/projects/ecommerce ``` -------------------------------- ### Run GripMock with Stub and Proto Files Source: https://github.com/bavix/gripmock/blob/master/examples/projects/faker/README.md Start GripMock using either the source code or an installed binary, specifying the stub and proto files. ```bash go run main.go --stub examples/projects/faker/stub.yaml examples/projects/faker/service.proto ``` ```bash gripmock --stub examples/projects/faker/stub.yaml examples/projects/faker/service.proto ``` -------------------------------- ### Start GripMock with a Proto File Source: https://github.com/bavix/gripmock/blob/master/README.md Start GripMock and load the service definition from a .proto file. ```bash gripmock service.proto ``` -------------------------------- ### Run the Validator Application Source: https://github.com/bavix/gripmock/blob/master/examples/projects/validator/README.md Starts the Gripmock server with the validator service definition and stubs. Ensure gripmock is installed. ```bash gripmock --stub examples/projects/validator examples/projects/validator/service.proto ``` -------------------------------- ### Install GripMock with Go Source: https://github.com/bavix/gripmock/blob/master/README.md Install GripMock using the Go toolchain. ```bash go install github.com/bavix/gripmock/v3@latest ``` -------------------------------- ### Start GripMock with Static Stubs Source: https://github.com/bavix/gripmock/blob/master/README.md Start GripMock with static stubs loaded from a directory and a .proto file. ```bash gripmock --stub stubs/ service.proto ``` -------------------------------- ### Run Echo Service Application Source: https://github.com/bavix/gripmock/blob/master/examples/projects/echo/README.md Starts the Echo Service application with a specified stub and proto definition. Ensure gripmock is installed. ```bash gripmock --stub examples/projects/echo examples/projects/echo/service_v1.proto ``` -------------------------------- ### Start GripMock with Reflection and Options Source: https://github.com/bavix/gripmock/blob/master/README.md Start GripMock using server reflection with various options like timeout, server name, or bearer token. ```bash gripmock grpc://localhost:50051?timeout=10s ``` ```bash gripmock grpcs://10.0.0.5:8443?serverName=api.company.local ``` ```bash gripmock grpc://localhost:50051?bearer= ``` -------------------------------- ### Start Greeter Server and Call via grpcurl Source: https://github.com/bavix/gripmock/blob/master/README.md Commands to start the GripMock server with the Greeter service and then call it using grpcurl. Ensure the stub and proto files are correctly specified. ```bash # Start server go run main.go examples/projects/greeter/service.proto --stub examples/projects/greeter # Call via grpcurl grpcurl -plaintext -d '{"name":"Alex"}' localhost:4770 helloworld.Greeter/SayHello ``` -------------------------------- ### Start GripMock Server Source: https://github.com/bavix/gripmock/blob/master/docs/guide/api/descriptors.md This command starts the GripMock server. If you are running from the repository source, use the 'go run' command instead. ```bash gripmock ``` ```bash go run main.go ``` -------------------------------- ### Run Glob Matching Example Source: https://github.com/bavix/gripmock/blob/master/examples/projects/glob/README.md Execute the main application with glob pattern routing enabled. This command starts the service and loads stubs from the specified directory. ```bash go run main.go examples/projects/glob/service.proto --stub examples/projects/glob ``` -------------------------------- ### Start Calculator Server Source: https://github.com/bavix/gripmock/blob/master/examples/projects/calculator/README.md Starts the GripMock server for the calculator service. Ensure the service proto and stub directories are correctly specified. ```bash go run main.go examples/projects/calculator/service.proto --stub examples/projects/calculator ``` -------------------------------- ### Create Reusable Test Helper Functions in Go Source: https://github.com/bavix/gripmock/blob/master/docs/guide/embedded-sdk/best-practices.md Define helper functions to encapsulate common mock setup logic, making tests more concise and maintainable. This example shows how to set up a mock service and client. ```go func runMyServiceMock(t *testing.T, opts ...sdk.Option) (sdk.Mock, MyServiceClient) { t.Helper() // ARRANGE // Add default options allOpts := []sdk.Option{ sdk.WithFileDescriptor(service.File_service_proto), } allOpts = append(allOpts, opts...) mock, err := sdk.Run(t, allOpts...) if err != nil { t.Fatalf("Failed to start GripMock: %v", err) } client := NewMyServiceClient(mock.Conn()) return mock, client } func TestMyService_WithHelper(t *testing.T) { // ARRANGE mock, client := runMyServiceMock(t) // Define stubs in the Arrange phase mock.Stub(sdk.By(MyService_MyMethod_FullMethodName)). When(sdk.Equals("id", "test")), Reply(sdk.Data("result", "success")), Commit() // ACT resp, err := client.MyMethod(t.Context(), &MyRequest{Id: "test"}) // ASSERT require.NoError(t, err) require.Equal(t, "success", resp.Result) } ``` -------------------------------- ### Start GripMock Server with Stub Source: https://github.com/bavix/gripmock/blob/master/examples/projects/nested-messages/README.md Use this command to start the GripMock server with a specific stub file for testing nested messages. ```bash gripmock --stub examples/projects/nested-messages examples/projects/nested-messages/service.proto ``` -------------------------------- ### Run GripMock with Self-Hosted BSR Source: https://github.com/bavix/gripmock/blob/master/docs/guide/sources/bsr.md Start GripMock using API definitions from a self-hosted BSR installation. Configure the base URL and token using BSR_SELF_BASE_URL and BSR_SELF_TOKEN environment variables. ```bash # Self-hosted BSR BSR_SELF_BASE_URL=https://bsr.company.local \ BSR_SELF_TOKEN= \ gripmock --stub ./stubs bsr.company.local/team/payments ``` ```bash BSR_SELF_BASE_URL=https://bsr.company.local \ BSR_SELF_TOKEN= \ gripmock --stub ./stubs bsr.company.local/team/payments:main ``` -------------------------------- ### Install GripMock using Homebrew Source: https://github.com/bavix/gripmock/blob/master/docs/guide/introduction/quick-usage.md Install GripMock on macOS and Linux using the official Homebrew repository. This is the recommended installation method. ```bash brew tap gripmock/tap ``` ```bash brew install --cask gripmock ``` ```bash gripmock --version ``` -------------------------------- ### Install GripMock with PowerShell Source: https://github.com/bavix/gripmock/blob/master/README.md Install GripMock on Windows using PowerShell. ```powershell irm https://raw.githubusercontent.com/bavix/gripmock/refs/heads/master/setup.ps1 | iex ``` -------------------------------- ### Install GripMock with Shell Script Source: https://github.com/bavix/gripmock/blob/master/README.md Install GripMock using a shell script downloaded from GitHub. ```bash curl -s https://raw.githubusercontent.com/bavix/gripmock/refs/heads/master/setup.sh | sh -s ``` -------------------------------- ### Start GripMock Server with Docker Source: https://github.com/bavix/gripmock/blob/master/examples/projects/nested-messages/README.md Run GripMock using Docker, mounting the proto files to the container for server startup. ```bash docker run -p 4770:4770 -p 4771:4771 \ -v $(pwd)/examples/projects/nested-messages:/proto \ bavix/gripmock /proto ``` -------------------------------- ### Run Identifier Service with GripMock Source: https://github.com/bavix/gripmock/blob/master/examples/projects/identifier/README.md Starts the Identifier Service using GripMock, specifying the stub directory and the protocol buffer service definition file. Ensure gripmock is installed and in your PATH. ```bash gripmock --stub examples/projects/identifier examples/projects/identifier/service.proto ``` -------------------------------- ### Quick Start GitHub Action for GripMock Source: https://github.com/bavix/gripmock/blob/master/docs/guide/ci-cd/github-actions.md This is a basic GitHub Actions workflow that checks out code, starts GripMock with specified proto sources and stubs, and then runs tests. ```yaml name: test on: [push, pull_request] jobs: e2e: runs-on: ubuntu-latest steps: - uses: actions/checkout@v5 - name: Start GripMock uses: bavix/gripmock-action@v1 with: source: proto/service.proto stub: stubs - name: Run tests run: go test ./... ``` -------------------------------- ### Basic Embedded SDK Usage Source: https://github.com/bavix/gripmock/blob/master/docs/guide/embedded-sdk/quick-start.md Demonstrates how to start an embedded GripMock instance, define a stub with a condition, and make a client call. ```go import ( "testing" "github.com/stretchr/testify/require" sdk "github.com/bavix/gripmock/v3/pkg/sdk" ) func TestMyService_Call(t *testing.T) { // ARRANGE mock, err := sdk.Run(t, sdk.WithFileDescriptor(helloworld.File_helloworld_proto)) require.NoError(t, err) // Define a stub mock.Stub(sdk.By(MyService_MyMethod_FullMethodName)). When(sdk.Equals("id", "test-id")), Reply(sdk.Data("result", "success")), Commit() client := NewMyServiceClient(mock.Conn()) // ACT reply, err := client.MyMethod(t.Context(), &MyRequest{Id: "test-id"}) // ASSERT require.NoError(t, err) require.Equal(t, "success", reply.GetResult()) } ``` -------------------------------- ### Start gripmock with YAML stub Source: https://github.com/bavix/gripmock/blob/master/examples/projects/track-streaming/README.md Use this command to start the gripmock server with a specified YAML stub file and service definition. This enables the defined gRPC services and their mock behaviors. ```bash gripmock --stub=./stubs.yaml ./service.proto ``` -------------------------------- ### Start Gripmock with String Processor Service Source: https://github.com/bavix/gripmock/blob/master/examples/projects/string-processor/README.md Starts the gripmock server with the string processor service definition and stub. ```bash go run main.go examples/projects/string-processor --stub examples/projects/string-processor ``` -------------------------------- ### Install GripMock SDK using Go Modules Source: https://github.com/bavix/gripmock/blob/master/docs/guide/embedded-sdk/installation.md Add the GripMock SDK to your Go project dependencies. Ensure you have Go 1.26 or later installed. ```bash go get github.com/bavix/gripmock/v3/pkg/sdk ``` -------------------------------- ### Example Contract Definition Source: https://github.com/bavix/gripmock/blob/master/docs/guide/api/stubs/unused-list.md Defines the gRPC service and messages for the example. ```proto syntax = "proto3"; package simple; service Gripmock { rpc SayHello (Request) returns (Reply); } message Request { string name = 1; } message Reply { string message = 1; int32 returnCode = 2; } ``` -------------------------------- ### Complex Example with Delay Source: https://github.com/bavix/gripmock/blob/master/docs/guide/embedded-sdk/quick-start.md Shows how to configure a stub with a simulated network delay before replying, useful for testing timeout scenarios. ```go import ( "testing" "time" "github.com/stretchr/testify/require" sdk "github.com/bavix/gripmock/v3/pkg/sdk" ) func TestGreeter_SayHello_WithDelay(t *testing.T) { // ARRANGE mock, err := sdk.Run(t, sdk.WithFileDescriptor(helloworld.File_helloworld_proto)) require.NoError(t, err) // Define a stub with delay delayMs := 20 mock.Stub(sdk.By(Greeter_SayHello_FullMethodName)). When(sdk.Equals("name", "Bob")), Reply(sdk.Data("message", "Hello Bob")), Delay(time.Duration(delayMs) * time.Millisecond), Commit() client := helloworld.NewGreeterClient(mock.Conn()) // ACT start := time.Now() reply, err := client.SayHello(t.Context(), &helloworld.HelloRequest{Name: "Bob"}) elapsed := time.Since(start) // ASSERT require.NoError(t, err) require.Equal(t, "Hello Bob", reply.GetMessage()) require.GreaterOrEqual(t, elapsed.Milliseconds(), int64(delayMs)) } ``` -------------------------------- ### Run GripMock Service Source: https://github.com/bavix/gripmock/blob/master/examples/projects/fingerprint/README.md Starts the GripMock server with the fingerprint service stubs and proto definition. ```bash gripmock --stub examples/projects/fingerprint examples/projects/fingerprint/service.proto ``` -------------------------------- ### Full Stub Example with Faker Source: https://github.com/bavix/gripmock/blob/master/docs/guide/stubs/faker.md A comprehensive example demonstrating the integration of various faker keys for generating diverse data fields within a service stub. ```yaml - service: example.UserService method: GetProfile input: matches: id: "\\d+" output: data: id: "{{.Request.id}}" first_name: "{{faker.Person.FirstName}}" last_name: "{{faker.Person.LastName}}" email: "{{faker.Contact.Email}}" city: "{{faker.Geo.City}}" lat: "{{faker.Geo.Latitude}}" lon: "{{faker.Geo.Longitude}}" ip: "{{faker.Network.IPv4}}" user_agent: "{{faker.Network.UserAgent}}" company: "{{faker.Company.Company}}" product: "{{faker.Commerce.ProductName}}" bio: "{{faker.Text.Paragraph 1}}" created_at: "{{faker.DateTime.PastDate}}" account_id: "{{faker.Identity.UUID}}" ``` -------------------------------- ### V1 API Example (Still Works) Source: https://github.com/bavix/gripmock/blob/master/docs/guide/stubs/streaming.md This is a V1 API example for a simple request-response service. It uses the singular `input` field for matching. ```yaml service: ChatService method: SendMessage input: equals: user: "alice" output: data: success: true ``` -------------------------------- ### Test Command for Any Example Source: https://github.com/bavix/gripmock/blob/master/docs/guide/types/well-known-types.md Uses grpcurl to send a request with a google.protobuf.Any payload, specifying the type and value. ```sh grpcurl -plaintext -d '{ "payload": { "@type": "type.googleapis.com/google.protobuf.StringValue", "value": "test" } }' localhost:4770 wkt.DataService/StoreData ``` -------------------------------- ### GripMock Integration Test Example (.gctf) Source: https://github.com/bavix/gripmock/blob/master/CONTRIBUTING.md Example of an integration test file in .gctf format. Used for testing gRPC server functionality changes. ```yaml --- --- ENDPOINT --- helloworld.Greeter/SayHello --- REQUEST --- {"name": "Alex"} --- RESPONSE --- {"message": "Hello, Alex!"} ``` -------------------------------- ### State Management Example with Dynamic Template Source: https://github.com/bavix/gripmock/blob/master/docs/guide/stubs/dynamic-templates.md This example demonstrates how to use dynamic templates to manage state across requests. It uses functions like `split`, `index`, `now`, `unix`, `if`, `setState`, `add`, and `default` to construct dynamic output data and update state. ```yaml - service: example.Service method: ProcessOrder input: equals: user_id: "USER_123" output: data: order_id: "ORDER_{{.Request.user_id | split "_" | index 1}}_{{now | unix}}" processing_step: "{{if .State.step}}{{.State.step}}{{else}}1{{end}}" message: "{{setState "step" (add (.State.step | default 0) 1)}}Processing step {{.State.step}}" ``` -------------------------------- ### Basic Stub Example Source: https://github.com/bavix/gripmock/blob/master/README.md Defines a simple stub for a 'SayHello' method on the 'Greeter' service. It matches an exact input and provides a static output. ```yaml service: Greeter method: SayHello input: equals: name: "gripmock" output: data: message: "Hello GripMock!" ``` -------------------------------- ### Proto Definition for Any Example Source: https://github.com/bavix/gripmock/blob/master/docs/guide/types/well-known-types.md Defines a service and messages for demonstrating the google.protobuf.Any type for generic data storage. ```proto syntax = "proto3"; import "google/protobuf/any.proto"; package wkt; service DataService { rpc StoreData(DataRequest) returns (DataResponse) {} } message DataRequest { google.protobuf.Any payload = 1; } message DataResponse { bool success = 1; } ``` -------------------------------- ### V2 API Example (Recommended) Source: https://github.com/bavix/gripmock/blob/master/docs/guide/stubs/streaming.md This is a V2 API example for a simple request-response service, recommended for new implementations. It uses the `stream` field to indicate V2 and supports more advanced features. ```yaml service: ChatService method: SendMessage stream: # V2 indicator - equals: user: "alice" output: data: success: true ``` -------------------------------- ### Configure Stub with Headers Source: https://github.com/bavix/gripmock/blob/master/docs/guide/introduction/quick-usage.md Example of a stub configuration that includes headers for matching, such as authorization. ```json { "headers": { "equals": { "authorization": "Bearer token123" } }, "input": { ... }, "output": { ... } } ``` -------------------------------- ### Start GripMock in Reflection with Upstream Replay Mode Source: https://github.com/bavix/gripmock/blob/master/docs/guide/ci-cd/github-actions.md Configures GripMock to start in replay mode, connecting to an upstream gRPC service. Adjust the wait-timeout as needed for your upstream service readiness. ```yaml - name: Start replay mode uses: bavix/gripmock-action@v1 with: source: grpc+replay://localhost:50051 wait-timeout: 60s ``` -------------------------------- ### Output of Any Example Source: https://github.com/bavix/gripmock/blob/master/docs/guide/types/well-known-types.md The JSON response indicating the success of storing generic data. ```json { "success": true } ``` -------------------------------- ### Server Streaming Example Source: https://github.com/bavix/gripmock/blob/master/docs/guide/stubs/streaming.md Configure server streaming by defining the service, method, and the expected output stream. Each item in the stream is sent sequentially. ```yaml service: TrackService method: StreamTrack input: equals: stn: "MS#00001" output: stream: - stn: "MS#00001" latitude: 0.1 longitude: 0.005 speed: 45 - stn: "MS#00001" latitude: 0.10001 longitude: 0.00501 speed: 46 ``` -------------------------------- ### Run GripMock for Auth Service Source: https://github.com/bavix/gripmock/blob/master/examples/projects/auth/README.md Starts GripMock to serve the authentication service using the provided proto definition and stub configurations. ```bash gripmock --stub examples/projects/auth examples/projects/auth/service.proto ``` -------------------------------- ### Example Workflow: Compile and Run with Buf Descriptor Source: https://github.com/bavix/gripmock/blob/master/docs/guide/introduction/advanced-usage.md Compile a proto descriptor using Buf and then run GripMock with the generated descriptor mounted as a volume. This ensures all services and dependencies are bundled into a single artifact. ```bash buf build -o api.pb ``` ```bash docker run \ -v $(pwd)/api.pb:/proto/api.pb \ -v $(pwd)/stubs:/stubs \ bavix/gripmock \ --stub=/stubs \ /proto/api.pb ``` -------------------------------- ### Safe Mock Initialization with Error Checking Source: https://github.com/bavix/gripmock/blob/master/docs/guide/embedded-sdk/best-practices.md Always check for errors when starting the mock server to ensure it initializes correctly. This prevents unexpected test failures due to mock setup issues. ```go func runSafeMock(t *testing.T) (sdk.Mock, MyServiceClient) { t.Helper() // ARRANGE mock, err := sdk.Run(t, sdk.WithFileDescriptor(service.File_service_proto)) require.NoError(t, err, "Failed to start GripMock - check proto file path and syntax") client := NewMyServiceClient(mock.Conn()) return mock, client } func TestMyService_WithSafeMock(t *testing.T) { // ARRANGE mock, client := runSafeMock(t) mock.Stub(sdk.By(MyService_MyMethod_FullMethodName)). When(sdk.Equals("id", "safe-test")). Reply(sdk.Data("result", "safe-success")), Commit() // ACT resp, err := client.MyMethod(t.Context(), &MyRequest{Id: "safe-test"}) // ASSERT require.NoError(t, err) require.Equal(t, "safe-success", resp.Result) } ``` -------------------------------- ### Plugin Replacement Example Source: https://github.com/bavix/gripmock/blob/master/docs/guide/plugins/advanced.md Specify a 'Replacement' to use an alternative function instead of the one defined by 'Fn'. This is useful for aliasing or substituting functions. ```go plugins.FuncSpec{ Name: "md5", Fn: md5Function, Replacement: "sha256", } ``` -------------------------------- ### Example Workflow: Compile and Run with Protoc Descriptor Source: https://github.com/bavix/gripmock/blob/master/docs/guide/introduction/advanced-usage.md Compile proto definitions into a descriptor set using protoc, including all imports, and then run GripMock with the descriptor. This approach pre-compiles and validates all proto definitions before runtime. ```bash protoc \ -I ./protos \ --descriptor_set_out=api.pb \ --include_imports \ common/*.proto services/*.proto ``` ```bash docker run \ -v $(pwd)/api.pb:/proto/api.pb \ -v $(pwd)/stubs:/stubs \ bavix/gripmock \ --stub=/stubs \ /proto/api.pb ``` -------------------------------- ### Quick Start: Running a Mock Server in Tests Source: https://github.com/bavix/gripmock/blob/master/pkg/sdk/README.md Initializes and runs a GripMock server within a test. It requires a testing.T and automatically registers cleanup functions for verification and closing. ```go mock, err := sdk.Run(t, sdk.WithFileDescriptor(helloworld.File_service_proto)) require.NoError(t, err) mock.Stub(sdk.By(helloworld.Greeter_SayHello_FullMethodName)). Unary("name", "Alex", "message", "Hi Alex"). Commit() client := helloworld.NewGreeterClient(mock.Conn()) reply, _ := client.SayHello(t.Context(), &helloworld.HelloRequest{Name: "Alex"}) // reply.Message == "Hi Alex" ``` -------------------------------- ### Example Workflow: Create, Search, and Retrieve Used Stubs Source: https://github.com/bavix/gripmock/blob/master/docs/guide/api/stubs/used-list.md This workflow demonstrates the typical usage pattern: first creating a stub, then performing a search that marks it as used, and finally retrieving the list of used stubs. ```bash curl -X POST -d '{ "service": "Gripmock", "method": "SayHello", "input": { "equals": { "name": "gripmock" } }, "output": { "data": { "message": "Hello GripMock", "return_code": 42 } } }' http://127.0.0.1:4771/api/stubs ``` ```bash curl -X POST -d '{ "service": "Gripmock", "method": "SayHello", "data": { "name": "gripmock" } }' http://127.0.0.1:4771/api/stubs/search ``` ```bash curl http://127.0.0.1:4771/api/stubs/used ``` -------------------------------- ### Install jsonschema Package Source: https://github.com/bavix/gripmock/blob/master/docs/guide/schema/validation.md Install the jsonschema package using pip, which is required for schema validation. ```bash pip install jsonschema ``` -------------------------------- ### Run GripMock with Multiple Proto Files (Docker) Source: https://github.com/bavix/gripmock/blob/master/docs/guide/introduction/quick-usage.md Start GripMock using Docker and specify multiple `.proto` files to mock several services. Ensure the proto files are mounted in the container. ```bash docker run \ -p 4770:4770 \ -p 4771:4771 \ -v ./protos:/proto:ro \ bavix/gripmock /proto/service1.proto /proto/service2.proto ``` -------------------------------- ### Start GripMock with Local Descriptors and Imports Source: https://github.com/bavix/gripmock/blob/master/docs/guide/modes/index.md Include the -i flag to specify directories for importing proto files when using local descriptors. ```bash gripmock -i ./proto -S ./proto/orders.proto grpc+capture://orders.api.internal:8443 ``` -------------------------------- ### Health Check Response Example Source: https://github.com/bavix/gripmock/blob/master/docs/guide/stubs/health.md Example JSON response for a health check, indicating the service status. ```json { "status": "NOT_SERVING" } ``` -------------------------------- ### BSR Fixture Project Example Source: https://github.com/bavix/gripmock/blob/master/docs/guide/sources/bsr.md Commands to set up, run tests, and tear down the BSR fixture project included in the repository. This is useful for testing BSR integration. ```bash cd third_party/bsr/eliza make up make test make down ``` -------------------------------- ### Testing Dynamic Templates with grpctestify Source: https://github.com/bavix/gripmock/blob/master/docs/guide/stubs/dynamic-templates.md This bash snippet shows the commands to start the Gripmock server with dynamic templates enabled and then run tests using `grpctestify`. ```bash # Start server go run main.go examples/projects/calculator/service.proto --stub examples/projects/calculator # Run tests grpctestify examples/projects/calculator ``` -------------------------------- ### Health Check Request Example Source: https://github.com/bavix/gripmock/blob/master/docs/guide/stubs/health.md Example JSON payload for a health check request targeting a specific service. ```json { "service": "examples.health.backend" } ``` -------------------------------- ### Example Unused Stub Response Source: https://github.com/bavix/gripmock/blob/master/docs/guide/api/stubs/unused-list.md An example of the JSON response when unused stubs are found. The response is an array of Stub objects. ```json [ { "id": "6c85b0fa-caaf-4640-a672-f56b7dd8074d", "service": "Gripmock", "method": "SayHello", "input": { "equals": { "name": "gripmock" } }, "output": { "data": { "message": "Hello GripMock", "returnCode": 42 }, "error": "" } } ] ``` -------------------------------- ### Basic Plugin Test Source: https://github.com/bavix/gripmock/blob/master/docs/guide/plugins/testing.md Demonstrates how to register a plugin, look up a function, and call it with a string argument, asserting the expected output. Ensure the plugin is registered using `Register(reg)` and the function exists. ```go package main import ( t"testing" "github.com/stretchr/testify/require" "github.com/bavix/gripmock/v3/pkg/plugintest" ) func TestMyPlugin(t *testing.T) { reg := plugintest.NewRegistry() Register(reg) fn := plugintest.MustLookupFunc(t, reg, "myfunction") result := plugintest.MustCall(t, fn, "test") require.Equal(t, "processed: test", result) } ``` -------------------------------- ### Run UnitConvertor Application (Using GripMock Binary) Source: https://github.com/bavix/gripmock/blob/master/examples/projects/unitconverter/README.md Run the UnitConvertor application using the pre-built GripMock binary. This command starts the mock server with stub configurations and the proto descriptor. ```bash gripmock --stub examples/projects/unitconverter examples/projects/unitconverter/service.pb ``` -------------------------------- ### Example Response for Used Stubs Source: https://github.com/bavix/gripmock/blob/master/docs/guide/api/stubs/used-list.md This is an example of the JSON response body when retrieving used stubs. It includes details of the matched stub. ```json [ { "id": "6c85b0fa-caaf-4640-a672-f56b7dd8074d", "service": "Gripmock", "method": "SayHello", "input": { "equals": { "name": "gripmock" } }, "output": { "data": { "message": "Hello GripMock", "return_code": 42 }, "error": "" } } ] ``` -------------------------------- ### Build and Load Go Plugin Source: https://github.com/bavix/gripmock/blob/master/docs/guide/plugins/index.md Compile your Go plugin using the 'plugin' build mode and then specify the plugin file path to the gripmock command. For production compatibility, use the builder image matching your GripMock version. ```bash go build -buildmode=plugin -o myplugin.so ./path/to/plugin gripmock --plugins=./myplugin.so service.proto ``` -------------------------------- ### Multi-Source Mode Binding Example Source: https://github.com/bavix/gripmock/blob/master/docs/guide/modes/index.md Illustrates how different modes apply to services registered from distinct sources, with the first source winning for overlapping services. ```bash gripmock \ grpc+proxy://proxy:123 \ grpc+replay://proxy1:321 \ grpc+capture://proxy2:444 ``` -------------------------------- ### Test Glob Matching Example Source: https://github.com/bavix/gripmock/blob/master/examples/projects/glob/README.md Run automated tests for the glob matching example using grpctestify. This command verifies the stub routing configurations. ```bash grpctestify examples/projects/glob/ ``` -------------------------------- ### Load mixed sources from a directory with GripMock Source: https://github.com/bavix/gripmock/blob/master/docs/guide/sources/index.md Load all supported files (.proto, .pb, .protoset) recursively from a specified directory. ```bash gripmock ./proto ``` -------------------------------- ### Run GripMock with Single Proto File (Docker) Source: https://github.com/bavix/gripmock/blob/master/docs/guide/introduction/quick-usage.md Start GripMock using Docker, exposing gRPC and HTTP ports, and mounting a local directory containing a single proto file. This is for mocking a single service defined in a .proto file. ```bash docker run \ -p 4770:4770 \ -p 4771:4771 \ -v ./api/proto:/proto:ro \ bavix/gripmock /proto/simple.proto ``` -------------------------------- ### Configure BSR Host Matching Source: https://github.com/bavix/gripmock/blob/master/docs/guide/sources/bsr.md Examples demonstrating how GripMock routes modules based on host matching for public and self-hosted BSR instances. Configure BSR_BUF_BASE_URL and BSR_BUF_TOKEN for public BSR, and BSR_SELF_BASE_URL and BSR_SELF_TOKEN for self-hosted BSR. ```bash # 1. Public buf.build (default) BSR_BUF_BASE_URL=https://buf.build BSR_BUF_TOKEN= # Modules: buf.build/owner/repo → uses Buf profile # 2. Self-hosted BSR BSR_SELF_BASE_URL=https://bsr.company.local BSR_SELF_TOKEN= # Host extracted from BaseURL: bsr.company.local → modules with this host use Self profile ``` -------------------------------- ### Plugin Decorator Example Source: https://github.com/bavix/gripmock/blob/master/docs/guide/plugins/advanced.md Use decorators to wrap existing functions, allowing you to add pre- or post-processing logic. This example increments the return value of a decorated function. ```go plugins.FuncSpec{ Name: "add", Decorates: "@gripmock/add", Fn: func(base func(context.Context, ...any) (any, error)) func(context.Context, ...any) (any, error) { return func(ctx context.Context, args ...any) (any, error) { val, err := base(ctx, args...) if err != nil { return nil, err } switch v := val.(type) { case float64: return v + 1, nil case int: return v + 1, nil default: return val, nil } } }, } ``` -------------------------------- ### Example Request for Contains Input Match Source: https://github.com/bavix/gripmock/blob/master/docs/guide/api/stubs/search.md This is an example request that would match the stub using the 'contains' rule. It includes the required fields plus additional ones. ```json { "name": "gripmock", "details": { "code": 42 }, "tags": ["grpc", "mock"] } ``` -------------------------------- ### Build Go Plugin with Builder Image Source: https://github.com/bavix/gripmock/blob/master/docs/guide/plugins/builder-image.md Use this command to build a Go plugin using the builder image. Ensure the tag matches the runtime image tag. Mount the current directory as a work directory to access source files and output the plugin. ```bash docker run --rm \ -v "$PWD":/work \ -w /work \ bavix/gripmock:v3.7.1-builder \ sh -lc 'go build -buildmode=plugin -o ./plugins/myplugin.so ./cmd/myplugin' ``` -------------------------------- ### Run GripMock with Proto Folder Auto-Load (Docker) Source: https://github.com/bavix/gripmock/blob/master/docs/guide/introduction/quick-usage.md Run GripMock using Docker by mounting a directory containing multiple `.proto` and `.pb` files. GripMock will automatically load all definitions from the specified directory. ```bash docker run \ -p 4770:4770 \ -p 4771:4771 \ -v ./protos:/proto:ro \ bavix/gripmock /proto ``` -------------------------------- ### Example Request for Contains Header Match Source: https://github.com/bavix/gripmock/blob/master/docs/guide/api/stubs/search.md This is an example request that would match the stub using the 'contains' header rule. It includes the required headers plus additional ones. ```json { "headers": { "authorization": "Bearer token123", "user-agent": "curl/7.64.1", "x-api-key": "abc123", "x-foo": "bar" } } ``` -------------------------------- ### Start GripMock with gRPC Reflection Source: https://github.com/bavix/gripmock/blob/master/docs/guide/modes/index.md Use this command when the upstream exposes gRPC reflection. GripMock fetches descriptors, registers services, and exposes its own reflection endpoint. ```bash gripmock grpc+capture://orders.api.internal:8443 ``` -------------------------------- ### Run Greeter Server Source: https://github.com/bavix/gripmock/blob/master/examples/projects/greeter/README.md Command to run the Greeter server with dynamic stubbing. Specify the proto file and the stub directory. ```bash go run main.go examples/projects/greeter/service.proto --stub examples/projects/greeter ``` -------------------------------- ### Output of Duration Example Source: https://github.com/bavix/gripmock/blob/master/docs/guide/types/well-known-types.md The JSON response showing the serialized duration. ```json { "timeTaken": "330s" } ``` -------------------------------- ### Run GripMock with Loaded Plugin Source: https://github.com/bavix/gripmock/blob/master/docs/guide/plugins/builder-image.md Execute this command to run GripMock with a compiled plugin. Mount the directory containing the plugin and proto files. Ensure the GripMock image tag matches the builder image tag used for compilation. ```bash docker run --rm \ -p 4770:4770 -p 4771:4771 \ -v "$PWD/plugins":/plugins \ -v "$PWD/proto":/proto \ bavix/gripmock:v3.7.1 \ --plugins=/plugins/myplugin.so /proto/service.proto ``` -------------------------------- ### Load .proto files with GripMock Source: https://github.com/bavix/gripmock/blob/master/docs/guide/sources/index.md Load one or multiple proto files directly using the gripmock command. Specify the file paths as arguments. ```bash gripmock service.proto ``` ```bash gripmock api/service1.proto api/service2.proto ``` -------------------------------- ### Proto Definition for Duration Example Source: https://github.com/bavix/gripmock/blob/master/docs/guide/types/well-known-types.md Defines a service and messages for demonstrating the google.protobuf.Duration type. ```proto syntax = "proto3"; import "google/protobuf/duration.proto"; package wkt; service TaskService { rpc GetDuration(TaskRequest) returns (TaskResponse) {} } message TaskRequest { string taskId = 1; } message TaskResponse { google.protobuf.Duration timeTaken = 1; } ``` -------------------------------- ### Running Mock with Merged FileDescriptorSet Source: https://github.com/bavix/gripmock/blob/master/pkg/sdk/README.md Sets up a mock server using a single `FileDescriptorSet` that contains files from multiple services. This is achieved by merging individual descriptor sets before passing them to `WithDescriptors`. ```go // Option 3: single WithDescriptors with merged FileDescriptorSet fds := &descriptorpb.FileDescriptorSet{ File: append(fdsGreeter.GetFile(), fdsEcho.GetFile()...), } mock, err := sdk.Run(t, sdk.WithDescriptors(fds)) ``` -------------------------------- ### Empty Output Example Source: https://github.com/bavix/gripmock/blob/master/docs/guide/types/specialized-utility-types.md The expected JSON output for an RPC that returns an empty message. ```json {} ``` -------------------------------- ### Test Command for Duration Example Source: https://github.com/bavix/gripmock/blob/master/docs/guide/types/well-known-types.md Uses grpcurl to send a request and verify the Duration output. ```sh grpcurl -plaintext -d '{"taskId": "task_123"}' localhost:4770 wkt.TaskService/GetDuration ``` -------------------------------- ### Multiple Matching Strategies for SearchUsers Source: https://github.com/bavix/gripmock/blob/master/docs/guide/embedded-sdk/defining-stubs.md This example showcases defining multiple stubs for the same method using different matching strategies: exact, partial, and regex. Each stub is configured to reply with distinct results based on the input. ```go func TestUserService_SearchUsers(t *testing.T) { // ARRANGE mock, err := sdk.Run(t, sdk.WithFileDescriptor(user.File_user_service_proto)) require.NoError(t, err) // Exact match stub mock.Stub(sdk.By(UserService_SearchUsers_FullMethodName)). When(sdk.Equals("name", "exact-match")), Reply(sdk.Data("results", []any{ map[string]any{"id": "1", "name": "exact-match"}, })), Commit() // Partial match stub mock.Stub(sdk.By(UserService_SearchUsers_FullMethodName)). When(sdk.Contains("name", "partial")), Reply(sdk.Data("results", []any{ map[string]any{"id": "2", "name": "partial-result"}, })), Commit() // Regex match stub mock.Stub(sdk.By(UserService_SearchUsers_FullMethodName)). When(sdk.Matches("email", `^[a-zA-Z0-9._%+-]+@example\.com$`)), Reply(sdk.Data("results", []any{ map[string]any{"id": "3", "name": "regex-match"}, })), Commit() client := NewUserServiceClient(mock.Conn()) // ACT exactReply, err := client.SearchUsers(t.Context(), &SearchUsersRequest{Name: "exact-match"}) require.NoError(t, err) partialReply, err := client.SearchUsers(t.Context(), &SearchUsersRequest{Name: "partial-search"}) require.NoError(t, err) regexReply, err := client.SearchUsers(t.Context(), &SearchUsersRequest{Email: "test@example.com"}) require.NoError(t, err) // ASSERT require.Equal(t, "1", exactReply.Results[0].Id) require.Equal(t, "2", partialReply.Results[0].Id) require.Equal(t, "3", regexReply.Results[0].Id) } ``` -------------------------------- ### Basic Usage: TLS Endpoint Source: https://github.com/bavix/gripmock/blob/master/docs/guide/sources/grpc-reflection.md Start GripMock using a TLS-enabled gRPC endpoint for reflection. ```bash gripmock grpcs://api.company.local:443 ``` -------------------------------- ### Basic Usage: Insecure Endpoint Source: https://github.com/bavix/gripmock/blob/master/docs/guide/sources/grpc-reflection.md Start GripMock using an insecure gRPC endpoint for reflection. ```bash gripmock grpc://localhost:50051 ``` -------------------------------- ### Build and Load Gripmock Plugins Source: https://github.com/bavix/gripmock/blob/master/docs/guide/introduction/quick-usage.md Commands to build custom plugins and load them into Gripmock for extended functionality. ```bash # Build plugins make plugins # Load plugins gripmock --plugins=./plugins/hash.so --plugins=./plugins/math.so service.proto ``` -------------------------------- ### Gripmock SDK Run Options Source: https://github.com/bavix/gripmock/blob/master/pkg/sdk/README.md Configuration options available when running the Gripmock SDK. These options allow customization of the mock server's behavior, such as using generated descriptors, listening on specific addresses, or connecting to a remote Gripmock instance. ```APIDOC ## Run Options ### `WithFileDescriptor(fd)` Use generated descriptor (e.g. `helloworld.File_service_proto`). ### `WithDescriptors(fds)` Use `FileDescriptorSet` (one or more files); can be chained for multiple protos. ### `WithListenAddr(network, addr)` Listen on a real port (e.g. `"tcp", ":0"`). ### `WithRemote(grpcAddr, restURL)` Connect to an external GripMock (gRPC + REST). ### `Remote(grpcAddr)` Deprecated alias; derives REST URL automatically. ### `WithSession(id)` Session isolation for parallel tests (remote only). ### `WithSessionTTL(d)` Automatic cleanup window for session resources (remote only). ### `WithGRPCTimeout(d)` Default per-RPC timeout for remote gRPC calls. ``` -------------------------------- ### FieldMask Output Example Source: https://github.com/bavix/gripmock/blob/master/docs/guide/types/specialized-utility-types.md The expected JSON output from a successful partial resource update using FieldMask. ```json { "success": true } ``` -------------------------------- ### Example: Invalid Priority Value Source: https://github.com/bavix/gripmock/blob/master/docs/guide/schema/validation.md Illustrates an invalid priority value, showing that 'priority' should be an integer, not a string. ```yaml priority: "high" # Should be integer ``` -------------------------------- ### Empty Example Proto Definition Source: https://github.com/bavix/gripmock/blob/master/docs/guide/types/specialized-utility-types.md Defines a HealthService that uses google.protobuf.Empty for both its request and response, suitable for health checks. ```proto syntax = "proto3"; import "google/protobuf/empty.proto"; package specialized; service HealthService { rpc CheckHealth(google.protobuf.Empty) returns (google.protobuf.Empty) {} } ``` -------------------------------- ### Basic Stub Definition and Usage Source: https://github.com/bavix/gripmock/blob/master/docs/guide/embedded-sdk/defining-stubs.md This example demonstrates setting up a basic stub for a `GetUser` request with an exact ID match. The stub is defined in the Arrange phase and then used in the Act phase. ```go func TestUserService_GetUser(t *testing.T) { // ARRANGE mock, err := sdk.Run(t, sdk.WithFileDescriptor(user.File_user_service_proto)) require.NoError(t, err) // Define stubs in the Arrange phase mock.Stub(sdk.By(UserService_GetUser_FullMethodName)). When(sdk.Equals("id", "user-123")), Reply(sdk.Data("name", "John Doe", "email", "john@example.com")), Commit() client := NewUserServiceClient(mock.Conn()) // ACT reply, err := client.GetUser(t.Context(), &GetUserRequest{Id: "user-123"}) // ASSERT require.NoError(t, err) require.Equal(t, "John Doe", reply.GetName()) require.Equal(t, "john@example.com", reply.GetEmail()) } ``` -------------------------------- ### Example: Invalid Input Matcher Source: https://github.com/bavix/gripmock/blob/master/docs/guide/schema/validation.md Highlights an incorrect input matcher where 'equals' is provided as a string instead of an object. ```yaml input: equals: "string" # Should be object ``` -------------------------------- ### Run Validator Tests with grpctestify Source: https://github.com/bavix/gripmock/blob/master/examples/projects/validator/README.md Executes tests for the validator service using the grpctestify tool. Ensure grpctestify is installed. ```bash grpctestify examples/projects/validator/ ``` -------------------------------- ### Running a Mock Server in Tests Source: https://github.com/bavix/gripmock/blob/master/pkg/sdk/README.md Initializes a GripMock server for use in tests. It requires a testing.T instance and automatically registers cleanup functions. ```APIDOC ## Run ### Description Initializes a GripMock server for use in tests. It requires a testing.T instance and automatically registers cleanup functions. ### Method Signature `sdk.Run(t testing.T, opts ...sdk.Option) (*sdk.Mock, error)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Options - `sdk.WithFileDescriptor(descriptor proto.FileDescriptor)`: Use generated file descriptors. - `sdk.WithDescriptors(descriptorSet *descriptorpb.FileDescriptorSet)`: Use FileDescriptorSet from protoc or buf. ### Request Example ```go mock, err := sdk.Run(t, sdk.WithFileDescriptor(helloworld.File_service_proto)) require.NoError(t, err) ``` ### Response #### Success Response (200) - `*sdk.Mock`: A GripMock instance. - `error`: An error if initialization fails. ``` -------------------------------- ### Run Tests with grpctestify Source: https://github.com/bavix/gripmock/blob/master/examples/projects/echo/README.md Executes tests for the Echo Service project using the grpctestify tool. Ensure grpctestify is installed. ```bash grpctestify examples/projects/echo/ ``` -------------------------------- ### Docker Configuration for Multiple Proto Files Source: https://github.com/bavix/gripmock/blob/master/docs/guide/introduction/advanced-usage.md Configure Docker to mount proto files and stubs, specifying the proto import path and listing all required proto files for the GripMock command. ```yaml services: gripmock: image: bavix/gripmock volumes: - ./src/proto:/proto:ro - ./mocks/user:/stubs:ro command: | --stub=/stubs \ --imports=/proto \ /proto/user/user.proto \ /proto/common/address.proto ``` -------------------------------- ### Optional Session Header Source: https://github.com/bavix/gripmock/blob/master/docs/guide/api/mcp/index.md This is an example of an optional HTTP request header that can be used to specify a session for calls to the MCP API. ```text X-Gripmock-Session: qa-run-42 ``` -------------------------------- ### FieldMask Example Proto Definition Source: https://github.com/bavix/gripmock/blob/master/docs/guide/types/specialized-utility-types.md Defines a service and request/response messages for demonstrating FieldMask usage in partial resource updates. ```proto syntax = "proto3"; import "google/protobuf/field_mask.proto"; package specialized; service ResourceService { rpc UpdateResource(UpdateRequest) returns (UpdateResponse) {} } message UpdateRequest { string resourceId = 1; google.protobuf.FieldMask updateMask = 2; } message UpdateResponse { bool success = 1; } ``` -------------------------------- ### Reasonable Delays Source: https://github.com/bavix/gripmock/blob/master/docs/guide/stubs/streaming.md Example showing a reasonable delay configuration for stream messages. Avoid excessively long delays in tests. ```yaml # Good delay: 500ms ```