sdk

package
v3.23.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 1, 2026 License: MIT Imports: 32 Imported by: 0

README

GripMock SDK

Go SDK for embedding a gRPC mock server in tests or connecting to a remote GripMock instance.

Quick start

srv := sdk.NewServer(t, sdk.WithFileDescriptor(helloworld.File_service_proto))
defer srv.Close()

srv.ExpectUnary("/helloworld.Greeter/SayHello").
    Match("name", "Alex").
    Return("message", "Hi Alex")

client := helloworld.NewGreeterClient(srv.Conn())
resp, _ := client.SayHello(t.Context(), &helloworld.HelloRequest{Name: "Alex"})
// resp.Message == "Hi Alex"

NewServer creates an independent server (safe for t.Parallel()), starts it on a random TCP port, and registers t.Cleanup for auto-verify + close.

Unary with delay:

srv.ExpectUnary("/svc/Method").
    Match("field", "value").
    Return(Delay(100*time.Millisecond, "responseField", "responseValue"))

Unary with sequential responses (NextWillReturn):

srv.ExpectUnary("/svc/Method").
    Match("step", "first").
    Return("result", "ok").
    NextWillReturn("result", "again")
// 1st call → {result: ok}, 2nd call → {result: again}, 3rd call → error

Server Stream:

srv.ExpectServerStream("/svc/Stream").
    Match("query", "test").
    SendStream(
        map[string]any{"id": "1", "title": "result 1"},
        map[string]any{"id": "2", "title": "result 2"},
    )

Client Stream:

srv.ExpectClientStream("/svc/Stream").
    Match(sdk.Matches("value", "\\d+")).
    Return("result", 42.0)

Bidirectional Stream:

srv.ExpectBidirectionalStream("/svc/Bidi").
    Run(func(ctx context.Context, stream any) error {
        return nil
    })

Effects (register side-effect stubs on match):

effect := sdk.Upsert("svc", "NextMethod").
    Match("step", "complete").
    Return("status", "done").
    Build()

srv.ExpectUnary("/svc/Method").
    Match("step", "begin").
    Effect(effect).
    Return("status", "started")

Verification:

err := srv.ExpectationsWereMet()
n := srv.Called("/svc/Method")
total := srv.TotalCalls()
history := srv.History()

Matchers for fine-grained matching:

// Equals (default), Contains, Matches (regex), Glob
srv.ExpectUnary("/svc/Method").
    Match("name", sdk.Contains("partial")).
    Match(sdk.Matches("email", `.*@example\.com$`)).
    Match(sdk.Glob("path", "prefix/**/suffix")).
    Match("exact_field", "exact_value").
    Return("result", "matched")

// Header matching — same universal matchers, pass to WithHeader/WithHeaders
srv.ExpectUnary("/svc/Method").
    WithHeader(sdk.Contains("authorization", "Bearer ")).
    Return("result", "auth_ok")

// AnyOf, And, IgnoreArrayOrder for complex conditions
srv.ExpectUnary("/svc/Method").
    Match(sdk.AnyOf(
        sdk.Equals("status", "active"),
        sdk.Equals("status", "pending"),
    )).
    Return("result", "ok")
Advanced features

Priority (higher wins):

srv.ExpectUnary("/svc/Method").
    Match("id", "specific").
    Priority(100).Return("result", "specific")

srv.ExpectUnary("/svc/Method").
    Match(sdk.Contains("id", "")).
    Priority(10).Return("result", "generic")

Times (call limit):

srv.ExpectUnary("/svc/Method").
    Match("id", "limited").
    Times(3).Return("result", "ok")
// Only matches 3 times, 4th call returns error

ReturnError:

srv.ExpectUnary("/svc/Method").
    Match("amount", 0).
    ReturnError(codes.InvalidArgument, "amount must be positive")

Migration from the legacy API (removed in v3.20.0)

Key differences
Legacy (removed in v3.20.0) Current
sdk.Run(t, opts...) sdk.NewServer(t, opts...)
mock.Stub(svc, method).Unary(...).Commit() srv.ExpectUnary(fullMethod).Match(...).Return(...)
sdk.By(fullMethod) use full method string directly
mock.Verify().Method(...).Called(t, n) srv.Called(fullMethod)
mock.History() srv.History()
mock.Stub(...).Delay(d).Commit() Return(Delay(d, ...)) or SendStream(Delay(d, ...))
mock.Stub(...).WhenStream(...) ExpectClientStream(...).Match(...)
mock.Stub(...).ReplyStream(...) ExpectServerStream(...).SendStream(...)
Removed in v3.16.0
  • sdk.By(), sdk.ParseFullMethodName(), sdk.StubBatch() — use full method strings directly
  • MockFrom() → WithReflection()
  • Remote() → WithRemote() (auto-derives REST URL from gRPC address)
  • WithServiceDesc() — no-op, removed
  • WithPayloadFunc() — no-op, removed
  • bufconn — default is now TCP :0 (real address like 127.0.0.1:PORT)
  • MergeHeaders(), MergeOutput() — replaced by Matcher-based API
New in v2
  • 4 dedicated expectation types: UnaryExpectation, ServerStreamExpectation, ClientStreamExpectation, BidirectionalExpectation
  • NextWillReturn(kv...) — sequential responses
  • Delay(d, kv...) — composable delay inside Return
  • Effect(Upsert(...).Build()) — side effects on match
  • WithBatch() — optional batching for remote mode
  • Server.Reset() — clear state without stopping server
  • Server.Flush() — flush pending stubs (batch mode)
  • Server.Address() — get listen address
  • Unified Matcher type: Equals, Contains, Matches, Glob, AnyOf, And for payload AND header matching (pass to Match() for payload, WithHeader() for headers)

Options

Option Description
WithFileDescriptor(fd) Use generated descriptor (e.g. helloworld.File_service_proto)
WithDescriptors(fds) Use FileDescriptorSet (one or more files); can be chained
WithProtoFiles(paths...) Compile .proto files at test time
WithListenAddr(network, addr) Listen on a specific address (default: :0)
WithRemote(grpcAddr, restURL) Connect to an external GripMock
WithSession(id) Session isolation for parallel tests
WithSessionTTL(d) Opt-in idle timer for session cleanup (off by default; reset by every SDK call)
WithGRPCTimeout(d) Per-RPC timeout for remote gRPC calls
WithHealthCheckTimeout(d) Readiness check timeout
WithReflection(addr) Load descriptors via gRPC reflection
WithHTTPClient(c) Custom HTTP client for remote mode
WithBatch() Enable stub batching for remote mode (flush via Flush())

Remote mode

srv := sdk.NewServer(t,
    sdk.WithRemote("localhost:4770", "http://localhost:4771"),
    sdk.WithSession("suite-A"),
)
defer srv.Close()

srv.ExpectUnary("/helloworld.Greeter/SayHello").
    Match("name", "Alex").
    Return("message", "Hi Alex")

client := helloworld.NewGreeterClient(srv.Conn())

Use WithBatch() to queue stubs and send them all at once via Flush():

srv := sdk.NewServer(t, sdk.WithRemote("localhost:4770", "http://localhost:4771"), sdk.WithBatch())
defer srv.Close()

srv.ExpectUnary("/svc/M").Match("k", "v").Return("r", "1")
srv.ExpectUnary("/svc/M").Match("k2", "v2").Return("r", "2")
srv.Flush() // sends both stubs in one REST call

Lifecycle methods

srv := sdk.NewServer(t, opts...)
srv.Address()               // "127.0.0.1:PORT"
srv.Conn()                  // *grpc.ClientConn
srv.Reset()                 // clear state without stopping
srv.Flush()                 // flush pending stubs (batch mode)
srv.Called("/svc/Method")   // call count
srv.TotalCalls()            // total call count
srv.History()               // all recorded calls
srv.ExpectationsWereMet()   // verify Times expectations
srv.Close()                 // stop + cleanup

Installation

go get github.com/bavix/gripmock/v3/pkg/sdk
Removed in v3.20.0

sdk.Run, sdk.Mock, sdk.StubBuilder, sdk.Verifier, sdk.MethodVerifier, sdk.HistoryReader, sdk.Merge (use sdk.And), Server.Stub, Server.Verify, Server.Addr (use Server.Address).

Reaching the full stub surface

Every expectation type accepts the same building blocks:

Method Sets
WithID(uuid) a fixed stub ID, so upsert/delete can target it across runs
Session(id) scopes the stub to one X-Gripmock-Session
ReturnHeaders / ReturnTrailers response metadata (templates are rendered per call)
Priority, Times, Once, Twice ranking and call budget
Effect(...) side-effect stubs, before or after the terminal method

Per shape:

Method Where Purpose
ReturnValue(v) unary, client stream reply with a scalar, array or null — Return always builds an object
ReturnProto(msg) / ReturnJSON(v) unary, client stream reply built from a proto message or an arbitrary Go value
ReturnStatus(code) all four a status code with no message
ReturnError / ReturnErrorWithDetails all four gRPC status, optionally with google.rpc.* details
Delay(d) all four pause before the reply, or before every streamed message; SendStream(Delay(d, ...)) delays one message
sdk.StreamError(code, msg, details...) stream element abort the stream at that position
MatchSequence(...) client stream, bidi positional matchers, one per message
Match + SendStream bidi a static bidi stub — the only bidi form that works in remote mode
Run(fn) unary, server stream, client stream, bidi an in-process handler; embedded mode only

Documentation

Overview

Package sdk provides an embedded gRPC mock server for tests.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrDescriptorsRequired                = errors.New("gripmock: descriptors required (use WithDescriptors or MockFrom)")
	ErrNoUsableServicesFoundViaReflection = errors.New("no services found via reflection (or only grpc.reflection/grpc.health)")
	ErrUnexpectedResponse                 = errors.New("unexpected response: not ListServicesResponse")
	ErrVerificationFailed                 = errors.New("gripmock: expectations not met")
	ErrInvalidInput                       = errors.New("gripmock: invalid input")
	ErrReflection                         = errors.New("gripmock: reflection error")
)
View Source
var ErrServerNotHealthy = errors.New("gripmock: server did not become healthy")

Functions

This section is empty.

Types

type BidirectionalExpectation added in v3.16.0

type BidirectionalExpectation struct {
	// contains filtered or unexported fields
}

BidirectionalExpectation builds a bidi-stream mock expectation.

func (*BidirectionalExpectation) Delay added in v3.20.0

Delay holds every message of the stream back by d.

func (*BidirectionalExpectation) Effect added in v3.16.0

Effect attaches side effects to a bidirectional-stream expectation.

func (*BidirectionalExpectation) Match added in v3.20.0

func (*BidirectionalExpectation) MatchSequence added in v3.20.0

func (e *BidirectionalExpectation) MatchSequence(matchers ...Matcher) *BidirectionalExpectation

MatchSequence matches the incoming messages positionally.

func (*BidirectionalExpectation) Once added in v3.20.0

func (*BidirectionalExpectation) Priority added in v3.16.0

func (*BidirectionalExpectation) ReturnError added in v3.20.0

ReturnError fails the exchange with a gRPC status instead of answering.

func (*BidirectionalExpectation) ReturnErrorWithDetails added in v3.20.0

func (e *BidirectionalExpectation) ReturnErrorWithDetails(
	code codes.Code,
	msg string,
	details ...map[string]any,
) *BidirectionalExpectation

func (*BidirectionalExpectation) ReturnHeaders added in v3.20.0

func (e *BidirectionalExpectation) ReturnHeaders(headers map[string]string) *BidirectionalExpectation

func (*BidirectionalExpectation) ReturnStatus added in v3.20.0

ReturnStatus fails the exchange with a bare gRPC status code and no message.

func (*BidirectionalExpectation) ReturnTrailers added in v3.20.0

func (e *BidirectionalExpectation) ReturnTrailers(trailers map[string]string) *BidirectionalExpectation

func (*BidirectionalExpectation) Run added in v3.16.0

Run executes a custom handler for this bidi expectation.

func (*BidirectionalExpectation) SendStream added in v3.20.0

func (e *BidirectionalExpectation) SendStream(items ...any) *BidirectionalExpectation

func (*BidirectionalExpectation) SendStreamTemplate added in v3.22.0

func (e *BidirectionalExpectation) SendStreamTemplate(document string) *BidirectionalExpectation

func (*BidirectionalExpectation) Session added in v3.20.0

Session isolates this stub to a specific session (X-Gripmock-Session header).

func (*BidirectionalExpectation) StubID added in v3.16.0

func (b *BidirectionalExpectation) StubID() string

Available after calling a terminal method (Return, SendStream, Run).

func (*BidirectionalExpectation) Times added in v3.16.0

func (*BidirectionalExpectation) Twice added in v3.20.0

func (*BidirectionalExpectation) WithHeader added in v3.16.0

func (e *BidirectionalExpectation) WithHeader(headers ...Matcher) *BidirectionalExpectation

func (*BidirectionalExpectation) WithID added in v3.20.0

type BidirectionalHandler added in v3.16.0

type BidirectionalHandler func(ctx context.Context, stream any) error

BidirectionalHandler processes a bidirectional stream.

type CallRecord

type CallRecord = history.CallRecord

CallRecord is a recorded gRPC call. Re-export for SDK users.

type ClientStreamExpectation added in v3.16.0

type ClientStreamExpectation struct {
	// contains filtered or unexported fields
}

ClientStreamExpectation builds a client-stream mock expectation.

func (*ClientStreamExpectation) Delay added in v3.20.0

Delay holds the response back before the reply is sent.

func (*ClientStreamExpectation) Effect added in v3.16.0

func (e *ClientStreamExpectation) Effect(effects ...*Effect) *ClientStreamExpectation

Effect attaches side effects to a client-stream expectation.

func (*ClientStreamExpectation) Match added in v3.16.0

func (e *ClientStreamExpectation) Match(matches ...any) *ClientStreamExpectation

Match accepts key-value pairs (shorthand for Equals on payload) or Matcher values.

func (*ClientStreamExpectation) MatchSequence added in v3.20.0

func (e *ClientStreamExpectation) MatchSequence(matchers ...Matcher) *ClientStreamExpectation

func (*ClientStreamExpectation) Once added in v3.20.0

func (*ClientStreamExpectation) Priority added in v3.16.0

func (*ClientStreamExpectation) Return added in v3.16.0

func (*ClientStreamExpectation) ReturnError added in v3.16.0

func (*ClientStreamExpectation) ReturnErrorWithDetails added in v3.20.0

func (e *ClientStreamExpectation) ReturnErrorWithDetails(
	code codes.Code,
	msg string,
	details ...map[string]any,
) *ClientStreamExpectation

ReturnErrorWithDetails returns a gRPC error carrying google.rpc.* details.

func (*ClientStreamExpectation) ReturnHeaders added in v3.20.0

func (e *ClientStreamExpectation) ReturnHeaders(headers map[string]string) *ClientStreamExpectation

func (*ClientStreamExpectation) ReturnJSON added in v3.20.0

ReturnJSON marshals any value to JSON and uses it as response.

func (*ClientStreamExpectation) ReturnProto added in v3.20.0

ReturnProto marshals a proto.Message to JSON and uses it as response.

func (*ClientStreamExpectation) ReturnStatus added in v3.20.0

ReturnStatus replies with a bare gRPC status code and no message.

func (*ClientStreamExpectation) ReturnTemplate added in v3.22.0

func (e *ClientStreamExpectation) ReturnTemplate(document string) *ClientStreamExpectation

func (*ClientStreamExpectation) ReturnTrailers added in v3.20.0

func (e *ClientStreamExpectation) ReturnTrailers(trailers map[string]string) *ClientStreamExpectation

func (*ClientStreamExpectation) ReturnValue added in v3.20.0

func (*ClientStreamExpectation) Run added in v3.20.0

Run drains the request stream with fn and replies with its return value.

func (*ClientStreamExpectation) Session added in v3.20.0

Session isolates this stub to a specific session (X-Gripmock-Session header).

func (*ClientStreamExpectation) StubID added in v3.16.0

func (b *ClientStreamExpectation) StubID() string

Available after calling a terminal method (Return, SendStream, Run).

func (*ClientStreamExpectation) Times added in v3.16.0

func (*ClientStreamExpectation) Twice added in v3.20.0

func (*ClientStreamExpectation) WithHeader added in v3.16.0

func (e *ClientStreamExpectation) WithHeader(headers ...Matcher) *ClientStreamExpectation

func (*ClientStreamExpectation) WithID added in v3.20.0

type ClientStreamHandler added in v3.16.0

type ClientStreamHandler func(ctx context.Context, messages []any) (any, error)

type DelayItem added in v3.16.0

type DelayItem struct {
	Delay time.Duration
	Data  map[string]any
}

DelayItem wraps response data with a time delay.

func Delay added in v3.16.0

func Delay(d time.Duration, kv ...any) DelayItem

Delay wraps response data with a time delay.

type Effect added in v3.16.0

type Effect struct {
	// contains filtered or unexported fields
}

Effect is a side effect that executes after a stub is matched.

func DeleteStub added in v3.16.0

func DeleteStub(id string) *Effect

DeleteStub creates an effect that deletes a stub by ID on match.

type EffectBuilder added in v3.16.0

type EffectBuilder struct {
	// contains filtered or unexported fields
}

EffectBuilder builds a stub that is registered when the triggering stub is matched.

func Upsert added in v3.16.0

func Upsert(service, method string) *EffectBuilder

Upsert creates an effect that registers another stub on match.

func (*EffectBuilder) Build added in v3.16.0

func (b *EffectBuilder) Build() *Effect

func (*EffectBuilder) Match added in v3.16.0

func (b *EffectBuilder) Match(key string, value any) *EffectBuilder

Match adds an exact-equality matcher. Use MatchAny for contains/matches/glob.

func (*EffectBuilder) MatchAny added in v3.20.0

func (b *EffectBuilder) MatchAny(matchers ...Matcher) *EffectBuilder

func (*EffectBuilder) Priority added in v3.20.0

func (b *EffectBuilder) Priority(n int) *EffectBuilder

Priority ranks the effect stub against others for the same method.

func (*EffectBuilder) Return added in v3.16.0

func (b *EffectBuilder) Return(kv ...any) *EffectBuilder

func (*EffectBuilder) ReturnError added in v3.16.0

func (b *EffectBuilder) ReturnError(code codes.Code, msg string) *EffectBuilder

func (*EffectBuilder) ReturnErrorWithDetails added in v3.20.0

func (b *EffectBuilder) ReturnErrorWithDetails(code codes.Code, msg string, details ...map[string]any) *EffectBuilder

ReturnErrorWithDetails fails the effect stub with google.rpc.* details.

func (*EffectBuilder) ReturnHeaders added in v3.20.0

func (b *EffectBuilder) ReturnHeaders(headers map[string]string) *EffectBuilder

ReturnHeaders sets response metadata on the effect stub.

func (*EffectBuilder) ReturnTemplate added in v3.22.0

func (b *EffectBuilder) ReturnTemplate(document string) *EffectBuilder

ReturnTemplate makes the effect stub answer with a Go template, rendered per request against the child's own request rather than the parent's.

func (*EffectBuilder) ReturnTrailers added in v3.20.0

func (b *EffectBuilder) ReturnTrailers(trailers map[string]string) *EffectBuilder

ReturnTrailers sets trailing metadata on the effect stub.

func (*EffectBuilder) SendStream added in v3.20.0

func (b *EffectBuilder) SendStream(items ...any) *EffectBuilder

SendStream makes the effect stub answer with a server stream.

func (*EffectBuilder) SendStreamTemplate added in v3.22.0

func (b *EffectBuilder) SendStreamTemplate(document string) *EffectBuilder

SendStreamTemplate makes the effect stub answer with a stream computed by a Go template.

func (*EffectBuilder) Session added in v3.20.0

func (b *EffectBuilder) Session(id string) *EffectBuilder

Session scopes the effect stub to one session.

func (*EffectBuilder) Times added in v3.20.0

func (b *EffectBuilder) Times(n int) *EffectBuilder

Times limits how many calls the effect stub may answer.

func (*EffectBuilder) WithHeader added in v3.20.0

func (b *EffectBuilder) WithHeader(headers ...Matcher) *EffectBuilder

WithHeader matches request metadata on the effect stub.

func (*EffectBuilder) WithID added in v3.20.0

func (b *EffectBuilder) WithID(id uuid.UUID) *EffectBuilder

WithID pins the effect stub's identifier so a later DeleteStub can target it.

type ExpectationNotMetError added in v3.16.0

type ExpectationNotMetError struct {
	Service  string
	Method   string
	Expected int
	Actual   int
}

ExpectationNotMetError describes a single unmet expectation for ExpectationsWereMet. Is(ErrVerificationFailed) returns true so callers can use errors.Is.

func (*ExpectationNotMetError) Error added in v3.16.0

func (e *ExpectationNotMetError) Error() string

func (*ExpectationNotMetError) Is added in v3.16.0

func (e *ExpectationNotMetError) Is(target error) bool

type InMemoryRecorder

type InMemoryRecorder = history.MemoryStore

InMemoryRecorder is the in-memory call recorder used by the embedded server.

type Matcher added in v3.16.0

type Matcher struct {
	// contains filtered or unexported fields
}

Matcher describes how to match a gRPC request field or header. Same type works for both payload fields and gRPC metadata headers. Created via Equals, Contains, Matches, Glob; composed via AnyOf, And.

Use Match(sdk.Contains(...)) for payload matching and WithHeader(sdk.Contains(...)) for gRPC metadata matching.

func And added in v3.16.0

func And(matchers ...Matcher) Matcher

And returns a Matcher that passes when all given matchers match (AND logic).

func AnyOf added in v3.16.0

func AnyOf(matchers ...Matcher) Matcher

AnyOf returns a Matcher that passes when at least one alternative matches (OR logic).

func Contains

func Contains(key string, value any) Matcher

func Equals

func Equals(key string, value any) Matcher

func Glob added in v3.16.0

func Glob(key, pattern string) Matcher

func IgnoreArrayOrder

func IgnoreArrayOrder(m Matcher) Matcher

func Matches

func Matches(key, pattern string) Matcher

type Option

type Option func(*options)

func WithBatch added in v3.16.0

func WithBatch() Option

WithBatch enables batch mode for remote stub registration.

func WithDescriptors

func WithDescriptors(fds *descriptorpb.FileDescriptorSet) Option

WithDescriptors appends files from the FileDescriptorSet to the mock server (skips duplicates by name).

func WithFileDescriptor

func WithFileDescriptor(fd protoreflect.FileDescriptor) Option

WithFileDescriptor appends a generated protoreflect.FileDescriptor (e.g. helloworld.File_service_proto).

func WithGRPCTimeout added in v3.7.1

func WithGRPCTimeout(d time.Duration) Option

WithGRPCTimeout sets default per-RPC timeout for remote gRPC calls.

func WithHTTPClient added in v3.7.1

func WithHTTPClient(client *http.Client) Option

WithHTTPClient overrides the HTTP client used by WithRemote mode for REST API calls.

func WithHealthCheckTimeout added in v3.7.1

func WithHealthCheckTimeout(d time.Duration) Option

func WithListenAddr

func WithListenAddr(network, addr string) Option

WithListenAddr sets network and address for real port listening. The default is a loopback port (127.0.0.1:0), which is also the address the server reports.

func WithProtoFiles added in v3.16.0

func WithProtoFiles(paths ...string) Option

func WithReflection added in v3.16.0

func WithReflection(addr string) Option

WithReflection resolves descriptors from a running gRPC server via reflection.

func WithRemote added in v3.7.1

func WithRemote(grpcAddr string, restURL string) Option

WithRemote configures the mock to connect to an external gripmock process.

func WithSession

func WithSession(sessionID string) Option

WithSession sets the session ID for isolation.

func WithSessionTTL added in v3.7.1

func WithSessionTTL(d time.Duration) Option

WithSessionTTL configures automatic cleanup time for session-scoped remote resources.

type Server added in v3.16.0

type Server struct {
	// contains filtered or unexported fields
}

Server is a running gRPC mock server (v2 API).

func NewServer added in v3.16.0

func NewServer(t TestingT, opts ...Option) *Server

NewServer creates and starts a mock server.

func (*Server) Address added in v3.16.0

func (s *Server) Address() string

Address returns the server address (e.g. "127.0.0.1:PORT").

func (*Server) Called added in v3.16.0

func (s *Server) Called(fullMethod string) int

Called returns the number of times a method was called.

func (*Server) Close added in v3.16.0

func (s *Server) Close() error

Close flushes pending stubs in batch mode and shuts down the server.

func (*Server) Conn added in v3.16.0

func (s *Server) Conn() *grpc.ClientConn

func (*Server) ExpectBidirectionalStream added in v3.16.0

func (s *Server) ExpectBidirectionalStream(fullMethod string) *BidirectionalExpectation

ExpectBidirectionalStream terminal: Run.

func (*Server) ExpectClientStream added in v3.16.0

func (s *Server) ExpectClientStream(fullMethod string) *ClientStreamExpectation

ExpectClientStream terminal: Return, ReturnError.

func (*Server) ExpectServerStream added in v3.16.0

func (s *Server) ExpectServerStream(fullMethod string) *ServerStreamExpectation

ExpectServerStream terminal: SendStream.

func (*Server) ExpectUnary added in v3.16.0

func (s *Server) ExpectUnary(fullMethod string) *UnaryExpectation

ExpectUnary terminal: Return, ReturnProto, ReturnError, Run.

func (*Server) ExpectationsWereMet added in v3.16.0

func (s *Server) ExpectationsWereMet() error

ExpectationsWereMet checks all expectations with non-zero Times were fulfilled.

func (*Server) ExpectationsWereMetContext added in v3.16.0

func (s *Server) ExpectationsWereMetContext(ctx context.Context) error

ExpectationsWereMetContext is the context-aware version of ExpectationsWereMet.

func (*Server) Flush added in v3.16.0

func (s *Server) Flush() error

Flush is a no-op for embedded mode and non-batch remote mode.

func (*Server) History added in v3.16.0

func (s *Server) History() []CallRecord

func (*Server) Reset added in v3.16.0

func (s *Server) Reset()

func (*Server) TotalCalls added in v3.16.0

func (s *Server) TotalCalls() int

type ServerStreamBuilder added in v3.16.0

type ServerStreamBuilder struct {
	// contains filtered or unexported fields
}

ServerStreamBuilder extends ServerStreamExpectation for chaining additional stream messages.

func (*ServerStreamBuilder) NextWillReturn added in v3.16.0

func (b *ServerStreamBuilder) NextWillReturn(kv ...any) *ServerStreamBuilder

NextWillReturn registers a new stub with lower priority.

func (*ServerStreamBuilder) Send added in v3.16.0

Send accepts KV pairs or DelayItem: Send(Delay(100*ms, "msg", "hello")).

type ServerStreamExpectation added in v3.16.0

type ServerStreamExpectation struct {
	// contains filtered or unexported fields
}

ServerStreamExpectation builds a server-stream mock expectation.

func (*ServerStreamExpectation) Delay added in v3.20.0

func (*ServerStreamExpectation) Effect added in v3.16.0

func (e *ServerStreamExpectation) Effect(effects ...*Effect) *ServerStreamExpectation

Effect attaches side effects to a server-stream expectation.

func (*ServerStreamExpectation) Match added in v3.16.0

func (e *ServerStreamExpectation) Match(matches ...any) *ServerStreamExpectation

Match accepts key-value pairs (shorthand for Equals on payload) or Matcher values.

func (*ServerStreamExpectation) Once added in v3.16.0

func (*ServerStreamExpectation) Priority added in v3.16.0

func (*ServerStreamExpectation) ReturnError added in v3.20.0

ReturnError terminates the call with a gRPC status instead of a stream.

func (*ServerStreamExpectation) ReturnErrorWithDetails added in v3.20.0

func (e *ServerStreamExpectation) ReturnErrorWithDetails(
	code codes.Code,
	msg string,
	details ...map[string]any,
) *ServerStreamExpectation

func (*ServerStreamExpectation) ReturnHeaders added in v3.20.0

func (e *ServerStreamExpectation) ReturnHeaders(headers map[string]string) *ServerStreamExpectation

func (*ServerStreamExpectation) ReturnStatus added in v3.20.0

ReturnStatus terminates the call with a bare gRPC status code and no message.

func (*ServerStreamExpectation) ReturnTrailers added in v3.20.0

func (e *ServerStreamExpectation) ReturnTrailers(trailers map[string]string) *ServerStreamExpectation

func (*ServerStreamExpectation) Run added in v3.20.0

Run writes the response stream from fn instead of a static Output.Stream.

func (*ServerStreamExpectation) SendStream added in v3.16.0

func (e *ServerStreamExpectation) SendStream(items ...any) *ServerStreamBuilder

func (*ServerStreamExpectation) SendStreamTemplate added in v3.22.0

func (e *ServerStreamExpectation) SendStreamTemplate(document string) *ServerStreamExpectation

func (*ServerStreamExpectation) Session added in v3.20.0

Session isolates this stub to a specific session (X-Gripmock-Session header).

func (*ServerStreamExpectation) StubID added in v3.16.0

func (b *ServerStreamExpectation) StubID() string

Available after calling a terminal method (Return, SendStream, Run).

func (*ServerStreamExpectation) Times added in v3.16.0

func (*ServerStreamExpectation) Twice added in v3.16.0

func (*ServerStreamExpectation) WithHeader added in v3.16.0

func (e *ServerStreamExpectation) WithHeader(headers ...Matcher) *ServerStreamExpectation

func (*ServerStreamExpectation) WithID added in v3.20.0

type ServerStreamHandler added in v3.16.0

type ServerStreamHandler func(ctx context.Context, in any, stream any) error

ServerStreamHandler processes a server-stream request.

type StreamErrorItem added in v3.20.0

type StreamErrorItem struct {
	Code    codes.Code
	Message string
	Details []map[string]any
}

StreamErrorItem aborts a stream at this position instead of sending a message.

func StreamError added in v3.20.0

func StreamError(code codes.Code, msg string, details ...map[string]any) StreamErrorItem

type TestingT

type TestingT interface {
	Error(args ...any)
	Fail()
	Context() context.Context
	Cleanup(f func())
}

TestingT is the minimal interface for test assertions.

type UnaryExpectation added in v3.16.0

type UnaryExpectation struct {
	// contains filtered or unexported fields
}

UnaryExpectation builds a unary mock expectation.

func (*UnaryExpectation) Delay added in v3.20.0

Delay holds the response back before it is sent.

func (*UnaryExpectation) Effect added in v3.16.0

func (e *UnaryExpectation) Effect(effects ...*Effect) *UnaryExpectation

Effect attaches side effects to a unary expectation.

func (*UnaryExpectation) Match added in v3.16.0

func (e *UnaryExpectation) Match(matches ...any) *UnaryExpectation

Match accepts key-value pairs (shorthand for Equals on payload) or Matcher values.

func (*UnaryExpectation) NextWillReturn added in v3.16.0

func (e *UnaryExpectation) NextWillReturn(kv ...any) *UnaryExpectation

NextWillReturn chains sequential responses: 1st call→Return, 2nd→NextWillReturn, etc.

func (*UnaryExpectation) NextWillReturnError added in v3.16.0

func (e *UnaryExpectation) NextWillReturnError(code codes.Code, msg string) *UnaryExpectation

func (*UnaryExpectation) Once added in v3.16.0

func (*UnaryExpectation) Priority added in v3.16.0

func (e *UnaryExpectation) Priority(n int) *UnaryExpectation

func (*UnaryExpectation) Return added in v3.16.0

func (e *UnaryExpectation) Return(kv ...any) *UnaryExpectation

Return with optional Delay: Return(Delay(100*ms, "msg", "hello")).

func (*UnaryExpectation) ReturnError added in v3.16.0

func (e *UnaryExpectation) ReturnError(code codes.Code, msg string) *UnaryExpectation

ReturnError returns a gRPC error for the call.

func (*UnaryExpectation) ReturnErrorWithDetails added in v3.16.0

func (e *UnaryExpectation) ReturnErrorWithDetails(code codes.Code, msg string, details ...map[string]any) *UnaryExpectation

ReturnErrorWithDetails returns a gRPC error with additional error details.

func (*UnaryExpectation) ReturnHeaders added in v3.20.0

func (e *UnaryExpectation) ReturnHeaders(headers map[string]string) *UnaryExpectation

func (*UnaryExpectation) ReturnJSON added in v3.16.0

func (e *UnaryExpectation) ReturnJSON(v any) *UnaryExpectation

ReturnJSON marshals any value to JSON and uses it as response.

func (*UnaryExpectation) ReturnProto added in v3.16.0

func (e *UnaryExpectation) ReturnProto(msg proto.Message) *UnaryExpectation

ReturnProto marshals a proto.Message to JSON and uses it as response.

func (*UnaryExpectation) ReturnStatus added in v3.20.0

func (e *UnaryExpectation) ReturnStatus(code codes.Code) *UnaryExpectation

ReturnStatus replies with a bare gRPC status code and no message.

func (*UnaryExpectation) ReturnTemplate added in v3.22.0

func (e *UnaryExpectation) ReturnTemplate(document string) *UnaryExpectation

func (*UnaryExpectation) ReturnTrailers added in v3.20.0

func (e *UnaryExpectation) ReturnTrailers(trailers map[string]string) *UnaryExpectation

ReturnTrailers sets response metadata sent with the closing status.

func (*UnaryExpectation) ReturnValue added in v3.20.0

func (e *UnaryExpectation) ReturnValue(v any) *UnaryExpectation

ReturnValue replies with v verbatim, including scalars, arrays and null.

func (*UnaryExpectation) Run added in v3.16.0

func (*UnaryExpectation) Session added in v3.16.0

func (e *UnaryExpectation) Session(id string) *UnaryExpectation

Session isolates this stub to a specific session (X-Gripmock-Session header).

func (*UnaryExpectation) StubID added in v3.16.0

func (b *UnaryExpectation) StubID() string

Available after calling a terminal method (Return, SendStream, Run).

func (*UnaryExpectation) Times added in v3.16.0

func (e *UnaryExpectation) Times(n int) *UnaryExpectation

func (*UnaryExpectation) Twice added in v3.16.0

func (e *UnaryExpectation) Twice() *UnaryExpectation

func (*UnaryExpectation) WithHeader added in v3.16.0

func (e *UnaryExpectation) WithHeader(headers ...Matcher) *UnaryExpectation

func (*UnaryExpectation) WithID added in v3.20.0

func (e *UnaryExpectation) WithID(id uuid.UUID) *UnaryExpectation

type UnaryHandler added in v3.16.0

type UnaryHandler func(ctx context.Context, in any) (any, error)

UnaryHandler processes a unary gRPC request and returns a response.

Directories

Path Synopsis
internal
httpmock
Package httpmock provides a httptest server using the real gripmock REST handlers.
Package httpmock provides a httptest server using the real gripmock REST handlers.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址