Documentation
¶
Overview ¶
Package mockgrpc runs gRPC mock servers for tests, and for the vlatte command.
A server serves any method of the services whose generated code the program imports, or whose descriptor sets it was given with ConfigBuilder.Descriptors: no service needs registering. Mocks name methods, match the calls, and answer them, whatever their call type: unary, server, client or bidi streaming.
m := mockgrpc.MustNew(mockgrpc.Setup().InMemory())
m.MustStart()
t.Cleanup(m.Close)
m.MustMock(mockgrpc.Method("greeter.Greeter/SayHello").
Field("name", match.Equal("ann")).
Reply(mockgrpc.Message(&pb.HelloReply{Message: "hi ann"})))
client := pb.NewGreeterClient(m.MustDial())
Method starts a mock; its matchers read the call's metadata and its request, as protojson writes it with the field names of the .proto file. Message, Messages, JSON, Template, Status, Bidi, Echo and Func reply, Seq and Rand answer with other replies in turn or at random, Shared gives mocks one Replier, and From answers with what another server answers, which Server.StartRecording records as mock files. A reply that returns github.com/caffeine-projects/vlatte.ErrAbort or github.com/caffeine-projects/vlatte.ErrReset cuts the call's connection, after what it sent: see Replier. Mocks can be limited with Times, take part in scenarios, wait with Delay, and run on_complete events, such as webhooks. A server can keep a journal of its calls, which tests verify with the same builders, and serve an admin API. Mocks can also come from JSON or YAML files: see FromFile.
Example ¶
package main
import (
"context"
"fmt"
"github.com/caffeine-projects/vlatte/match"
"github.com/caffeine-projects/vlatte/mockgrpc"
pb "github.com/caffeine-projects/vlatte/mockgrpc/internal/protobuf"
)
func main() {
m := mockgrpc.MustNew(mockgrpc.Setup().Silent().InMemory())
m.MustStart()
defer m.Close()
m.MustMock(mockgrpc.Method("TestService/Greetings").
Field("message", match.Equal("hi")).
Reply(mockgrpc.Message(&pb.HiRes{Message: "hello"})))
res, err := pb.NewTestServiceClient(m.MustDial()).Greetings(context.Background(), &pb.HiReq{Message: "hi"})
if err != nil {
panic(err)
}
fmt.Println(res.GetMessage())
}
Output: hello
Index ¶
- Constants
- Variables
- func ConfigUsage() string
- func EncodeMock(mock *Mock, format string) ([]byte, error)
- func FromBytes(data []byte, format string) vlatte.Builder[*Mock, *Server]
- func FromFile(path string) vlatte.Builder[*Mock, *Server]
- func MockFileFormats() []string
- type AdminAPI
- type AdminStore
- type BidiReply
- func (b *BidiReply) Header(key string, values ...string) *BidiReply
- func (b *BidiReply) NewReplier(app *Server, methods []protoreflect.MethodDescriptor) (Replier, error)
- func (b *BidiReply) On(m vlatte.Matcher, r *Response) *BidiReply
- func (b *BidiReply) OnEnd(r *Response) *BidiReply
- func (b *BidiReply) Otherwise(r *Response) *BidiReply
- func (b *BidiReply) Trailer(key string, values ...string) *BidiReply
- type Builder
- func (b *Builder) Body(m vlatte.Matcher) *Builder
- func (b *Builder) Build(app *Server) (*Mock, error)
- func (b *Builder) CallMatches(fn func(call *Call) (bool, error)) *Builder
- func (b *Builder) Callback(fn vlatte.EventFunc[vlatte.OnComplete]) *Builder
- func (b *Builder) Delay(d vlatte.Delay) *Builder
- func (b *Builder) Enabled(enabled bool) *Builder
- func (b *Builder) Field(path string, m vlatte.Matcher) *Builder
- func (b *Builder) Header(key string, m vlatte.Matcher) *Builder
- func (b *Builder) ID(id string) *Builder
- func (b *Builder) JSON(text string) *Builder
- func (b *Builder) Matches(m vlatte.Matcher) *Builder
- func (b *Builder) Message(msg proto.Message) *Builder
- func (b *Builder) Messages(msgs ...proto.Message) *Builder
- func (b *Builder) Name(name string) *Builder
- func (b *Builder) OnCompleteEvent(cfg vlatte.EventConfig) *Builder
- func (b *Builder) Once() *Builder
- func (b *Builder) Priority(p int) *Builder
- func (b *Builder) Reply(r Reply) *Builder
- func (b *Builder) ScenarioIs(scenario string) *Builder
- func (b *Builder) ScenarioKey(tmpl string) *Builder
- func (b *Builder) ScenarioStateIs(requiredState string) *Builder
- func (b *Builder) ScenarioStateWillBe(newState string) *Builder
- func (b *Builder) SetSource(src string) *Builder
- func (b *Builder) StartScenario(name string) *Builder
- func (b *Builder) Times(times int64) *Builder
- type Call
- func (c *Call) Descriptor() protoreflect.MethodDescriptor
- func (c *Call) Header() metadata.MD
- func (c *Call) JSON() []byte
- func (c *Call) Message() proto.Message
- func (c *Call) Messages() []proto.Message
- func (c *Call) Method() string
- func (c *Call) NewOutput() proto.Message
- func (c *Call) Recv() (proto.Message, error)
- func (c *Call) Send(msg proto.Message) error
- func (c *Call) Sent() []proto.Message
- func (c *Call) Server() *Server
- type Config
- type ConfigBuilder
- func (cb *ConfigBuilder) Addr(addr string) *ConfigBuilder
- func (cb *ConfigBuilder) Admin(api AdminAPI) *ConfigBuilder
- func (cb *ConfigBuilder) AdminStore(store AdminStore) *ConfigBuilder
- func (cb *ConfigBuilder) Apply(conf *Config) error
- func (cb *ConfigBuilder) ConfigSources(sources ...ConfigSource) *ConfigBuilder
- func (cb *ConfigBuilder) ConnectionTimeout(timeout time.Duration) *ConfigBuilder
- func (cb *ConfigBuilder) Descriptors(paths ...string) *ConfigBuilder
- func (cb *ConfigBuilder) EventListeners(listeners *vlatte.Listener) *ConfigBuilder
- func (cb *ConfigBuilder) Files(files *protoregistry.Files) *ConfigBuilder
- func (cb *ConfigBuilder) GlobalEvents(events *vlatte.Events) *ConfigBuilder
- func (cb *ConfigBuilder) InMemory() *ConfigBuilder
- func (cb *ConfigBuilder) Journal(dir string) *ConfigBuilder
- func (cb *ConfigBuilder) KV(kv vlatte.KV) *ConfigBuilder
- func (cb *ConfigBuilder) Listener(l net.Listener) *ConfigBuilder
- func (cb *ConfigBuilder) LogLevel(l vlatte.LogLevel) *ConfigBuilder
- func (cb *ConfigBuilder) LogOutput(w io.Writer) *ConfigBuilder
- func (cb *ConfigBuilder) Logger(logger *zerolog.Logger) *ConfigBuilder
- func (cb *ConfigBuilder) Matchers(r *matchbuild.Registry) *ConfigBuilder
- func (cb *ConfigBuilder) MaxConnectionIdle(timeout time.Duration) *ConfigBuilder
- func (cb *ConfigBuilder) MockFiles(patterns ...string) *ConfigBuilder
- func (cb *ConfigBuilder) Name(name string) *ConfigBuilder
- func (cb *ConfigBuilder) NoDebugHeaders() *ConfigBuilder
- func (cb *ConfigBuilder) NoMatchCode(code codes.Code) *ConfigBuilder
- func (cb *ConfigBuilder) NoNearMisses() *ConfigBuilder
- func (cb *ConfigBuilder) OnCompleteListener(name string, listener vlatte.EventListener[vlatte.OnComplete]) *ConfigBuilder
- func (cb *ConfigBuilder) OutboundAllow(prefixes ...netip.Prefix) *ConfigBuilder
- func (cb *ConfigBuilder) OutboundDeny(prefixes ...netip.Prefix) *ConfigBuilder
- func (cb *ConfigBuilder) Record(options ...RecordConfigurer) *ConfigBuilder
- func (cb *ConfigBuilder) Reflection() *ConfigBuilder
- func (cb *ConfigBuilder) RootDir(dir string) *ConfigBuilder
- func (cb *ConfigBuilder) ServerOptions(options ...grpc.ServerOption) *ConfigBuilder
- func (cb *ConfigBuilder) Service(sd *grpc.ServiceDesc, impl any) *ConfigBuilder
- func (cb *ConfigBuilder) ShutdownTimeout(d time.Duration) *ConfigBuilder
- func (cb *ConfigBuilder) Silent() *ConfigBuilder
- func (cb *ConfigBuilder) TLSCertKeyPair(certFile, keyFile string) *ConfigBuilder
- func (cb *ConfigBuilder) TLSCertificates(certs []tls.Certificate) *ConfigBuilder
- func (cb *ConfigBuilder) TLSClientCAs(pool *x509.CertPool) *ConfigBuilder
- func (cb *ConfigBuilder) TLSConfig(c *tls.Config) *ConfigBuilder
- func (cb *ConfigBuilder) TLSMutual(certFile, keyFile, clientCAFile string) *ConfigBuilder
- func (cb *ConfigBuilder) TemplateDataProviders(providers ...TemplateDataProvider) *ConfigBuilder
- func (cb *ConfigBuilder) TemplateEngine(e vlatte.TemplateEngine) *ConfigBuilder
- func (cb *ConfigBuilder) TemplateEnv(names ...string) *ConfigBuilder
- func (cb *ConfigBuilder) TemplateKeys(specs ...string) *ConfigBuilder
- type ConfigFlag
- type ConfigSource
- type EchoReply
- type JournalConfig
- type KVView
- type Kit
- type MatcherSpec
- type Mock
- func (m *Mock) Called() bool
- func (m *Mock) Close() error
- func (m *Mock) Describe() vlatte.Descriptor
- func (m *Mock) Disable()
- func (m *Mock) Enable()
- func (m *Mock) Enabled() bool
- func (m *Mock) Events() vlatte.Events
- func (m *Mock) Hits() int64
- func (m *Mock) ID() string
- func (m *Mock) Inc()
- func (m *Mock) Methods() []string
- func (m *Mock) Name() string
- func (m *Mock) Origin() string
- func (m *Mock) Priority() int
- func (m *Mock) String() string
- type OnComplete
- func (i *OnComplete) Call() *Call
- func (i *OnComplete) Dir() string
- func (i *OnComplete) Kind() vlatte.Kind
- func (i *OnComplete) Kit() vlatte.Kit
- func (i *OnComplete) Logger() *zerolog.Logger
- func (i *OnComplete) Mock() vlatte.Mock
- func (i *OnComplete) Parameters() vlatte.Parameters
- func (i *OnComplete) Status() *status.Status
- type Option
- type ProxyReply
- type RandomReply
- type Recipe
- type RecordConfig
- type RecordConfigurer
- func RecordDialOptions(opts ...grpc.DialOption) RecordConfigurer
- func RecordDir(dir string) RecordConfigurer
- func RecordFormat(format string) RecordConfigurer
- func RecordIncludeMocked(v bool) RecordConfigurer
- func RecordMethods(methods ...string) RecordConfigurer
- func RecordRepeats(repeats vlatte.RecordRepeats) RecordConfigurer
- func RecordRequestHeaders(keys ...string) RecordConfigurer
- func RecordTarget(target string) RecordConfigurer
- func RecordTransform(transform func(*RecordedMock) error) RecordConfigurer
- type RecordedMock
- type RecordedRequest
- type RecordedResponse
- type RecordedStatus
- type Replier
- type ReplierFunc
- type Reply
- type Response
- func (r *Response) Details(details ...proto.Message) *Response
- func (r *Response) Header(key string, values ...string) *Response
- func (r *Response) MessageDelay(d vlatte.Delay) *Response
- func (r *Response) NewReplier(app *Server, methods []protoreflect.MethodDescriptor) (Replier, error)
- func (r *Response) Status(code codes.Code, msg string) *Response
- func (r *Response) Trailer(key string, values ...string) *Response
- type Scope
- type SequentialReply
- type Server
- func (app *Server) Addr() string
- func (app *Server) AdminURL() string
- func (app *Server) Certificate() *x509.Certificate
- func (app *Server) Close()
- func (app *Server) Config() *Config
- func (app *Server) Data() map[string]any
- func (app *Server) Dial(opts ...grpc.DialOption) (*grpc.ClientConn, error)
- func (app *Server) GRPCServer() *grpc.Server
- func (app *Server) IsRecording() bool
- func (app *Server) KV() vlatte.KV
- func (app *Server) MustDial(opts ...grpc.DialOption) *grpc.ClientConn
- func (app *Server) MustStart()
- func (app *Server) MustStartTLS()
- func (app *Server) Prep(ctx context.Context, recipes ...Recipe) error
- func (app *Server) RecordingStatus() vlatte.RecordStatus
- func (app *Server) RegisterService(desc *grpc.ServiceDesc, impl any)
- func (app *Server) Reload() error
- func (app *Server) RequestPattern(b vlatte.Builder[*Mock, *Server]) (verify.Pattern, error)
- func (app *Server) ResetScenario(name string, in ...matchscenario.Instance)
- func (app *Server) ResetScenarios()
- func (app *Server) Scenarios(ctx context.Context) ([]matchscenario.Scenario, error)
- func (app *Server) SetData(data map[string]any)
- func (app *Server) SetScenario(ctx context.Context, name, state string, in ...matchscenario.Instance) error
- func (app *Server) Start() error
- func (app *Server) StartRecording(options ...RecordConfigurer) error
- func (app *Server) StartTLS() error
- func (app *Server) StopRecording(ctx context.Context) (*vlatte.RecordResult, error)
- type TemplateData
- type TemplateDataProvider
- type TemplateDataProviderInput
- type TemplateRequest
Examples ¶
Constants ¶
const ( // DefaultConfigFileName is the base name of the config file DefaultConfigSources reads, the HTTP server's. DefaultConfigFileName = ".vlatterc" // EnvPrefix starts the names of the environment variables of the settings. EnvPrefix = "VLATTE" )
const Kind vlatte.Kind = "grpc"
Kind is the protocol of gRPC mock servers, the Kind of their journal entries.
Variables ¶
var ( // ErrUnknownMethod is the error of a mock whose method no descriptor of the server describes: a typo, or a service // whose generated code the program doesn't import and whose descriptors the server wasn't given. ErrUnknownMethod = errors.New("mock: unknown method") // ErrAmbiguousMethod is the error of a mock whose method name matches methods of different call types, such as a // unary and a streaming one of two services: name the service too. ErrAmbiguousMethod = errors.New("mock: ambiguous method") )
var DefaultConfigDirectories = []string{".", "testdata"}
DefaultConfigDirectories are where DefaultConfigSources looks for the config file, in order.
var ErrStreamInterceptorSlot = errors.New("journal: pass stream interceptors with grpc.ChainStreamInterceptor: " +
"the journal takes grpc.StreamInterceptor")
ErrStreamInterceptorSlot is the error of a server with a journal whose ServerOptions set the stream interceptor with grpc.StreamInterceptor, which grpc runs before every other: the journal takes it, to journal the code a call ends with. grpc.ChainStreamInterceptor gives the same interceptor.
Functions ¶
func ConfigUsage ¶
func ConfigUsage() string
ConfigUsage describes every server setting: its flag, environment variable, file key, allowed values and default.
func EncodeMock ¶
EncodeMock describes mock in format, json, yaml or yml, as the admin API's GET /mocks/{id} does: what a persistent store of the admin API keeps, such as a document of a database. DecodeMock builds the mock back. Relative body files are named from the working directory. A mock that can't be described fails.
func FromBytes ¶
FromBytes builds a mock from a JSON or YAML document, as FromFile does. format is json, yaml or yml. A relative body_file opens from the working directory. Multiple nonempty YAML documents are rejected.
func FromFile ¶
FromFile builds a mock from a JSON or YAML file, chosen by its extension: .json, .yaml or .yml.
id: greet-ann
request:
method: greeter.Greeter/SayHello
fields: {name: ann}
response:
message: {message: hello ann}
A relative body_file opens from the file's directory. When the file has problems, the error is a list of every one, each with its key and a hint. A YAML stream must contain one nonempty mock document: use ConfigBuilder.MockFiles to load multiple documents from a file.
func MockFileFormats ¶
func MockFileFormats() []string
MockFileFormats lists the formats of mock files, as file extensions without the dot.
Types ¶
type AdminAPI ¶
AdminAPI is a handle to the built-in admin API: a RESTful HTTP server of its own, the same as HTTP mock servers have. Make one with github.com/caffeine-projects/vlatte/admin.New. The operations gRPC mocks can't do, such as recording, answer 501.
type AdminStore ¶
AdminStore makes the persistent store of the mocks the admin API adds, for the server app. The store keeps their descriptions, by ID, such as in files or a database: EncodeMock describes a mock, and DecodeMock builds it back. The mocks of mock files and code never reach it.
func FileStore ¶
func FileStore(dir string) AdminStore
FileStore makes a persistent store of the mocks the admin API adds: a mock file each, <id>.mock.yaml in dir, as EncodeMock describes the mock. Only the store reads them: keep dir out of the mock file patterns, or its mocks would load twice. A relative dir starts at the server's root directory. A file a person adds, edits or removes takes effect on the server's next reload. A mock whose description doesn't load back is refused: its file would fail every later start. A file's mock must have the ID the file's name gives, as the store finds a mock's file by its name: one that doesn't fails the start and the reload.
type BidiReply ¶
type BidiReply struct {
// contains filtered or unexported fields
}
BidiReply describes the answer of a bidi streaming mock, message by message: each message the client sends gets the Response of the first rule whose matcher matches it, or of Otherwise. A Response that ends with a status other than OK ends the call there. Once the client closes its side, OnEnd's Response answers, and its status ends the call.
A message no rule matches, without Otherwise, gets no answer.
func Bidi ¶
func Bidi() *BidiReply
Bidi returns a BidiReply with no rules: one that answers nothing until the client closes its side, and then ends the call with OK.
Example ¶
package main
import (
"context"
"errors"
"fmt"
"io"
"github.com/caffeine-projects/vlatte/match"
"github.com/caffeine-projects/vlatte/mockgrpc"
pb "github.com/caffeine-projects/vlatte/mockgrpc/internal/protobuf"
)
func main() {
m := mockgrpc.MustNew(mockgrpc.Setup().Silent().InMemory())
m.MustStart()
defer m.Close()
m.MustMock(mockgrpc.Method("TestService/Chat").Reply(mockgrpc.Bidi().
On(match.Field("message", match.Equal("hi")), mockgrpc.Message(&pb.HiRes{Message: "hello"})).
Otherwise(mockgrpc.JSON(`{"message": "?"}`)).
OnEnd(mockgrpc.Message(&pb.HiRes{Message: "bye"}))))
stream, err := pb.NewTestServiceClient(m.MustDial()).Chat(context.Background())
if err != nil {
panic(err)
}
for _, msg := range []string{"hi", "what"} {
if err := stream.Send(&pb.HiReq{Message: msg}); err != nil {
panic(err)
}
res, err := stream.Recv()
if err != nil {
panic(err)
}
fmt.Println(res.GetMessage())
}
_ = stream.CloseSend()
for {
res, err := stream.Recv()
if errors.Is(err, io.EOF) {
break
}
fmt.Println(res.GetMessage())
}
}
Output: hello ? bye
func (*BidiReply) NewReplier ¶
func (b *BidiReply) NewReplier(app *Server, methods []protoreflect.MethodDescriptor) (Replier, error)
NewReplier implements Reply.
func (*BidiReply) On ¶
On answers each message m matches with r. m reads the message as JSON, as Builder.Field reads a request: match.Field("message", match.Equal("hi")). The rules run in the order they were added.
func (*BidiReply) OnEnd ¶
OnEnd answers with r once the client closed its side, and ends the call with r's status.
type Builder ¶
type Builder struct {
// contains filtered or unexported fields
}
Builder describes a mock of a gRPC method. Build makes a new Mock from it each time, for the given server, and leaves the builder as it was: one builder can be added to many servers, or more than once to one.
Mocks built from one builder share its matchers and delay. Each has its own ID (unless set with ID), hits, count of Times and Once, enabled state, scenario binding and Replier.
func Method ¶
Method starts a mock of a method, named by whole segments of its full method "/pkg.Service/Method": "Method", "Service/Method", "pkg.Service/Method" or the full method, such as a generated pb.Service_Method_FullMethodName. A part of a name, such as "Meth", names none.
The mock is built for the methods its name names: those of the services whose generated code the program imports, or whose descriptors the server was given with ConfigBuilder.Descriptors or ConfigBuilder.Files. Build fails with ErrUnknownMethod when it names none, and with ErrAmbiguousMethod when it names methods of different call types. The call type of the method decides how the mock serves it: unary, server, client or bidi streaming.
func (*Builder) Body ¶
Body matches the request as JSON text, as Field reads it, with m, such as match.Contain("ann") or match.EqualJSON(...).
func (*Builder) Build ¶
Build makes a new Mock for app from the builder, and leaves the builder as it was. Server.Mock calls it.
func (*Builder) CallMatches ¶
CallMatches matches a call fn reports true for. fn reads the call as matchers do, with its request: see Call. A mock file can't hold a function: describing a mock with it fails, so the admin API can't show the mock, nor save it.
func (*Builder) Callback ¶
Callback adds fn as an on_complete event of the mock, named callback in the logs, with no listener to register. It runs as the mock's other events and the global ones do: at the same time as them, once the mock replied, and the call ends after it, so a test checks what it did right after the call. fn gets an *OnComplete, read-only as the events run at the same time, and a context that the client leaving doesn't end, and Server.Close does. An error or a panic of fn is logged as a warning, and told by the call's journal entry, unless Close canceled it, and never changes the answer. Mock files can't set callbacks: describing a mock with one fails, as with Builder.CallMatches.
func (*Builder) Delay ¶
Delay chooses the wait before each reply. Nil disables it. A client that leaves during the wait gets no reply, and the mock does not count the call. An evaluation error prevents the reply.
func (*Builder) Enabled ¶
Enabled sets whether the mocks built afterwards start enabled. All mocks are enabled by default. A mock already built changes through its Scope.
func (*Builder) Field ¶
Field matches the request at path, a JSON path, such as "user_id" or "$.items[0].key", with m. The request is read as protojson writes it, with the field names of the .proto file: enums as names, int64 values as text. A client streaming call is read as the array of its messages, so "$[0].key" reads its first message.
func (*Builder) Header ¶
Header matches the metadata the client sent under key: its value, when it sent one, else all of them, nil when it sent none. gRPC metadata keys are lowercase.
func (*Builder) ID ¶
ID sets the ID of the mock, such as "greet-hi". Without one, each mock built gets a generated ID. An ID holds only letters, digits, '.', '_', '~' and '-', and a server holds one mock per ID.
func (*Builder) JSON ¶
JSON matches a request equal to the message text holds, by proto.Equal: text is read as protojson reads it, in the type of the method's request, so {"user_id": "u1", "count": 42} and {"userId": "u1", "count": "42"} match the same call. A client streaming call's text is an array of its messages. Build fails on text that holds no such message.
func (*Builder) Matches ¶
Matches adds a matcher of the whole call: m gets the *Call, as the function of CallMatches does. A mock file's request.custom adds matchers this way, such as custom ones of the server's registry: see ConfigBuilder.Matchers. Unlike a function, a matcher that describes itself is described, under request.custom, so the admin API's store keeps it. Describing a mock with a matcher that doesn't, here or in any other method, fails, as with Builder.CallMatches.
func (*Builder) Message ¶
Message matches a request message equal to msg, by proto.Equal: the request of a unary or server streaming call.
func (*Builder) Messages ¶
Messages matches the messages of a client streaming call, in order, each equal to its own by proto.Equal.
func (*Builder) Name ¶
Name sets a name for the mock, which debug headers, logs and assertion messages show.
func (*Builder) OnCompleteEvent ¶
func (b *Builder) OnCompleteEvent(cfg vlatte.EventConfig) *Builder
OnCompleteEvent adds an on_complete event to the mock, such as a webhook: it runs once the mock replied, and the call ends after it, unless cfg.AfterResponse is set: see vlatte.EventConfig.AfterResponse. Unless it carries its own Listener, its Name names a listener the server registered: see ConfigBuilder.OnCompleteListener. Describing a mock with an event that carries its own Listener fails, as with Builder.Callback.
func (*Builder) Priority ¶
Priority sets the priority of the mock. Mocks with a lower priority are matched first; mocks of equal priority, in the order they were added.
func (*Builder) Reply ¶
Reply sets what the mock replies with: Message, Messages, JSON, Template, Status, Bidi or Func. Build asks r for a new Replier for each mock, so r can serve many mocks.
func (*Builder) ScenarioIs ¶
ScenarioIs puts the mock in the given scenario. Without Builder.ScenarioStateIs, it matches in any state of it.
func (*Builder) ScenarioKey ¶
ScenarioKey sets the template of the key of the instance of the mock's scenario a call plays in, such as {{ with index .Request.Header "x-test-id" }}{{ index . 0 }}{{ end }}: each key is a scenario of its own, starting in started, so tests that run at once with keys of their own don't move each other's. It renders with the data of Template replies. It renders more than once for a call: as the mock matches, as it takes its turn and to journal the move, so a key reads the call only, never .Scenarios, a random value or the time. A key that renders empty plays in the shared instance, the one of mocks without a key. A template that fails to render fails the call's matching. Read a keyed instance with Server.Scenarios, and move it with Server.SetScenario and matchscenario.Key.
func (*Builder) ScenarioStateIs ¶
ScenarioStateIs sets that the mock matches only while its scenario is in requiredState.
func (*Builder) ScenarioStateWillBe ¶
ScenarioStateWillBe sets the state the scenario moves to when this mock is picked to answer a call, before it answers: the next call matches in that state. With Builder.ScenarioStateIs, of two calls in that state, only one gets this mock; without it, the mock matches in every state, so every call gets it. The scenario moves even when the mock then fails to answer, as when its client leaves during its delay.
func (*Builder) SetSource ¶
SetSource sets where the mock comes from, such as the mock file that describes it, which logs and the admin API show.
func (*Builder) StartScenario ¶
StartScenario sets that this mock starts a new scenario with the given name: it matches while the scenario is in its first state, "started".
type Call ¶
type Call struct {
// contains filtered or unexported fields
}
Call is a call a mock serves, as its matchers, replies, templates and events read it.
A unary or server streaming call has one request message, in Message. A client streaming call has all the messages the client sent, in Messages, once it closed its side. A bidi streaming call has the messages received so far: its mock matches before any, on the method and the header, and its reply reads them with Recv.
Its methods are safe for concurrent use, but Send and Recv, which follow grpc's streams: one goroutine at a time may call Send, and one Recv. The messages are the server's: don't change them.
func (*Call) Descriptor ¶
func (c *Call) Descriptor() protoreflect.MethodDescriptor
Descriptor returns the descriptor of the method of the call.
func (*Call) JSON ¶
JSON returns the request as JSON, as matchers, the journal and templates read it: the message of a unary or server streaming call, as protojson writes it with the field names of the .proto file, and an array of the messages of a streaming client, received so far.
func (*Call) Message ¶
Message returns the request message of a unary or server streaming call, nil for other calls.
func (*Call) Messages ¶
Messages returns the messages the client sent so far, in order: one for a unary or server streaming call.
func (*Call) NewOutput ¶
NewOutput returns a new, empty message of the type the method of the call answers with: a reply that builds its answer, such as Func's, fills it in.
func (*Call) Recv ¶
Recv receives the next message of a bidi streaming call, and returns io.EOF once the client closed its side. Other calls received their messages before the mock matched: see Message and Messages.
func (*Call) Send ¶
Send sends msg to the client. A unary or client streaming call answers one message: Send sets it, and the call sends it once the reply returns. A streaming server sends each message as Send gets it.
type Config ¶
type Config struct {
// Name names the server in its log lines.
Name string
// ConfigSources are the sources of settings New reads after the options, which they override: see
// DefaultConfigSources, which nil reads. An empty list reads none.
ConfigSources []ConfigSource
// Serve reports whether the settings turned the grpc section on: the vlatte command serves gRPC mocks then.
Serve bool
Service any
ServiceDesc *grpc.ServiceDesc
ServerOptions []grpc.ServerOption
Addr string
Listener net.Listener // in place of listening on Addr: see ConfigBuilder.Listener
// ConnectionTimeout bounds connection setup, including TLS and the HTTP/2 handshake. Zero keeps gRPC's
// default, 120s. Values must be nonnegative. A [grpc.ConnectionTimeout] in [Config.ServerOptions] overrides it.
// It does not impose a deadline on an RPC or stream after setup.
ConnectionTimeout time.Duration
// MaxConnectionIdle sends GOAWAY after a connection has had no active RPCs for this long. Zero keeps gRPC's
// default, no idle limit. Values must be nonnegative. A [grpc.KeepaliveParams] in [Config.ServerOptions] overrides it.
// An active RPC or stream keeps the connection busy, even while no messages are being exchanged.
MaxConnectionIdle time.Duration
// InMemory serves the server in memory, in place of listening on Addr: see ConfigBuilder.InMemory.
InMemory bool
// Reflection serves the gRPC server reflection service: see ConfigBuilder.Reflection.
Reflection bool
// UseTLS reports whether the settings turned TLS on: the vlatte command serves with Server.StartTLS then.
UseTLS bool
// TLSConfig is the TLS configuration Server.StartTLS serves. It wins over TLSCertificates and TLSClientCAs.
TLSConfig *tls.Config
// TLSCertificates are the certificates Server.StartTLS serves. Empty serves a self-signed one: see
// Server.Certificate.
TLSCertificates []tls.Certificate
// TLSClientCAs are the CAs that client certificates must be signed by: Server.StartTLS then requires one
// (mutual TLS).
TLSClientCAs *x509.CertPool
// Logger is the server's logger. Nil builds one that writes to the standard output, at LogLevel.
Logger *zerolog.Logger
// LogLevel is the level of the logger the server builds.
LogLevel vlatte.LogLevel
// LogOutput is where the logger the server builds writes. Nil is the standard output.
LogOutput io.Writer
// NoDebugHeaders turns off the debug header metadata, such as vlatte-matched-mock-id, of the server's answers.
NoDebugHeaders bool
// NoMatchCode is the code of the answer to a call no mock matched, with the vlatte-error trailer. OK means
// codes.NotFound.
NoMatchCode codes.Code
// Files holds the descriptors of services the program has no generated code of, which mocks can serve as if it
// had: see ConfigBuilder.Files.
Files *protoregistry.Files
// Descriptors are paths of descriptor set files, which the server loads as it does Files: see
// ConfigBuilder.Descriptors.
Descriptors []string
// Listeners holds the on_complete listeners mocks name, such as webhooks. Nil gives the server a registry of its
// own.
Listeners *vlatte.Listener
// GlobalEvents are the events that run for every mock.
GlobalEvents *vlatte.Events
// Matchers builds the matcher lists of mock files, and of the admin API's call queries: the built-in matchers and
// custom ones. Nil builds the built-in matchers only.
Matchers *matchbuild.Registry
// TemplateEngine compiles the templates of replies and events. Nil uses a vlatte.GoTemplateEngine.
TemplateEngine vlatte.TemplateEngine
// TemplateEnv names the environment variables templates may read with env, from the setting grpc.template.env.
// It configures the vlatte.GoTemplateEngine the server makes without a TemplateEngine, so setting both is an
// error: allow them on that engine with vlatte.WithEnv.
TemplateEnv []string
// TemplateKeys are the keys templates sign tokens with, jwt, and publish, jwks, from the setting
// grpc.template.keys: "kid=ALG" generates a key when the server is made, a new one each time, and
// "kid=ALG:path/to/key.pem" reads one, a relative path starting at RootDir. Like TemplateEnv, it configures the
// default engine only: add keys to an engine of your own with vlatte.WithSigningKey.
TemplateKeys []string
// TemplateDataProviders add data to templates, which read it as .Provided.<Key>. Two of the same key are an error.
TemplateDataProviders []TemplateDataProvider
// KV is the key-value store templates read as .KV. Nil keeps the values in memory.
KV vlatte.KV
// RootDir is where relative MockFiles patterns start. Empty is the working directory.
RootDir string
// MockFiles are glob patterns of the mock files the server loads at Start and on Reload.
MockFiles []string
// ShutdownTimeout is how long Close waits for the calls in flight before it cuts them. 0 means 5s.
ShutdownTimeout time.Duration
// Admin serves the admin API, on an HTTP server of its own. Nil serves none.
Admin AdminAPI
// AdminStore keeps the mocks the admin API adds in a persistent store: see ConfigBuilder.AdminStore. Nil keeps them
// in memory. It needs Admin.
AdminStore AdminStore
// Journal keeps a journal of the calls the server serves. Nil keeps none.
Journal *JournalConfig
// Record records the calls the server proxies as mock files, from Start to Close, and serves the recordings of its
// directory: see RecordConfig. Nil records nothing, until Server.StartRecording.
Record *RecordConfig
// NoNearMisses turns off the report of the mocks closest to a call no mock matched, which its journal entry
// lists. The report runs no matcher twice: it runs those matching never reached.
NoNearMisses bool
// OutboundAllow and OutboundDeny limit the addresses the server connects to, for its proxy replies, the recording
// target and webhooks: an address in OutboundDeny is refused, and so is one outside OutboundAllow when it isn't
// empty. Deny wins, and either one refuses the unspecified address, 0.0.0.0 or ::, which reaches this host. They
// check the address after DNS resolution, so a host name that resolves into a refused range is refused. An IPv4
// range doesn't hold IPv6 addresses: deny ::1/128 with 127.0.0.0/8. With either set, proxy replies and the
// recording target connect directly, never through the proxy of the environment; webhooks still do, and the rules
// check that proxy's address then. A target on a unix socket isn't a network address: they don't apply to it. A
// refused connection fails with [vlatte.ErrOutboundRefused]. Empty, the default, refuses nothing. A dialer of the
// caller's, a grpc.WithContextDialer in [ProxyReply.DialOptions] or [RecordConfig.DialOptions], or a webhook's
// own transport, dials on its own, and they don't apply.
OutboundAllow []netip.Prefix
OutboundDeny []netip.Prefix
}
Config configures a Server. As an Option, it sets every field of the server's configuration, its zero values included: Setup sets only what its methods set, so its options compose.
type ConfigBuilder ¶
type ConfigBuilder struct {
// contains filtered or unexported fields
}
ConfigBuilder builds the configuration of a Server. Each method sets one setting, and Apply sets only those: the options passed to New compose, so a later one changes only what it sets.
func (*ConfigBuilder) Addr ¶
func (cb *ConfigBuilder) Addr(addr string) *ConfigBuilder
Addr sets the address the server listens on. The default is a random local port: see Server.Addr.
func (*ConfigBuilder) Admin ¶
func (cb *ConfigBuilder) Admin(api AdminAPI) *ConfigBuilder
Admin serves the admin API api, such as admin.MustNew(admin.Addr("127.0.0.1:8081")), on an HTTP server of its own. Server.AdminURL returns where it listens.
func (*ConfigBuilder) AdminStore ¶
func (cb *ConfigBuilder) AdminStore(store AdminStore) *ConfigBuilder
AdminStore keeps the mocks the admin API adds in the persistent store store makes, such as FileStore(dir): each change the admin API makes reaches it at once, and the server serves what it holds when it starts and on each Reload, so changes made to it directly take effect too. Without one, those mocks stay in memory, as long as the server runs. It needs an admin API: see Admin.
func (*ConfigBuilder) Apply ¶
func (cb *ConfigBuilder) Apply(conf *Config) error
Apply implements Option: it sets, in order, what the methods of cb set, and leaves the rest of conf as it is.
func (*ConfigBuilder) ConfigSources ¶
func (cb *ConfigBuilder) ConfigSources(sources ...ConfigSource) *ConfigBuilder
ConfigSources sets the sources of settings New reads after the options, which they override: see DefaultConfigSources. Without it, New reads DefaultConfigSources(nil): the grpc section of .vlatterc, and the VLATTE_GRPC_* environment variables. Call it with none to read none.
func (*ConfigBuilder) ConnectionTimeout ¶ added in v1.1.0
func (cb *ConfigBuilder) ConnectionTimeout(timeout time.Duration) *ConfigBuilder
ConnectionTimeout sets the limit for connection setup: see Config.ConnectionTimeout.
func (*ConfigBuilder) Descriptors ¶
func (cb *ConfigBuilder) Descriptors(paths ...string) *ConfigBuilder
Descriptors gives the server the descriptor set files at paths, as Files does: such as protoc writes with --descriptor_set_out and --include_imports, or buf build -o. New fails on a file it can't read.
func (*ConfigBuilder) EventListeners ¶
func (cb *ConfigBuilder) EventListeners(listeners *vlatte.Listener) *ConfigBuilder
EventListeners sets the registry of named event listeners, such as one several servers share.
func (*ConfigBuilder) Files ¶
func (cb *ConfigBuilder) Files(files *protoregistry.Files) *ConfigBuilder
Files gives the server the descriptors of services the program has no generated code of: mocks name their methods, and the server serves their calls with messages of dynamic types. Generated code registers its own descriptors, in protoregistry.GlobalFiles, which the server always reads.
func (*ConfigBuilder) GlobalEvents ¶
func (cb *ConfigBuilder) GlobalEvents(events *vlatte.Events) *ConfigBuilder
GlobalEvents sets the events that run for every mock, before the mock's own.
func (*ConfigBuilder) InMemory ¶
func (cb *ConfigBuilder) InMemory() *ConfigBuilder
InMemory serves the server in memory, in place of listening on a port: only the connections of Server.Dial reach it. Tests that run in parallel need no free port, and nothing outside the test can call the server. New fails for a server given a Listener too.
func (*ConfigBuilder) Journal ¶
func (cb *ConfigBuilder) Journal(dir string) *ConfigBuilder
Journal keeps a journal of the calls the server serves, in dir, across restarts: see JournalConfig. Empty keeps it in a temporary directory, which Close removes, as a test wants: a named one keeps the calls of earlier runs.
func (*ConfigBuilder) KV ¶
func (cb *ConfigBuilder) KV(kv vlatte.KV) *ConfigBuilder
KV sets the key-value store templates read as .KV: {{ .KV.Get "key" }}. Without one, the server keeps the values in memory.
func (*ConfigBuilder) Listener ¶
func (cb *ConfigBuilder) Listener(l net.Listener) *ConfigBuilder
Listener sets an already bound listener for the mock GRPC server to serve instead of listening on Addr. Start takes it: Close, or a Start that fails, closes it, so nothing listens without a server behind it.
func (*ConfigBuilder) LogLevel ¶
func (cb *ConfigBuilder) LogLevel(l vlatte.LogLevel) *ConfigBuilder
LogLevel sets the level of the logger the server builds.
func (*ConfigBuilder) LogOutput ¶
func (cb *ConfigBuilder) LogOutput(w io.Writer) *ConfigBuilder
LogOutput sets where the logger the server builds writes, in place of the standard output, such as for a program that keeps the standard output for something else. A Logger writes where it was told to.
func (*ConfigBuilder) Logger ¶
func (cb *ConfigBuilder) Logger(logger *zerolog.Logger) *ConfigBuilder
Logger sets the logger of the server. Without one, the server logs to the standard output, at LogLevel.
func (*ConfigBuilder) Matchers ¶
func (cb *ConfigBuilder) Matchers(r *matchbuild.Registry) *ConfigBuilder
Matchers sets the registry that builds the matcher lists of the server's mock files, such as one that holds custom matchers: matchbuild.WithMatcher. Servers can share a registry. Nil builds the built-in matchers only.
func (*ConfigBuilder) MaxConnectionIdle ¶ added in v1.1.0
func (cb *ConfigBuilder) MaxConnectionIdle(timeout time.Duration) *ConfigBuilder
MaxConnectionIdle sets how long a connection with no active RPCs can stay idle: see Config.MaxConnectionIdle.
func (*ConfigBuilder) MockFiles ¶
func (cb *ConfigBuilder) MockFiles(patterns ...string) *ConfigBuilder
MockFiles adds glob patterns of mock files, such as "testdata/grpc/*.yaml", which the server loads at Start, before it serves, and again on Reload. See FromFile for their format.
func (*ConfigBuilder) Name ¶
func (cb *ConfigBuilder) Name(name string) *ConfigBuilder
Name names the server in its log lines.
func (*ConfigBuilder) NoDebugHeaders ¶
func (cb *ConfigBuilder) NoDebugHeaders() *ConfigBuilder
NoDebugHeaders turns off the debug header metadata, such as vlatte-matched-mock-id, that the server adds to its answers. The vlatte-error trailer stays: it tells the server's own answers from a mock's.
func (*ConfigBuilder) NoMatchCode ¶
func (cb *ConfigBuilder) NoMatchCode(code codes.Code) *ConfigBuilder
NoMatchCode sets the code of the answer to a call no mock matched. The default is codes.NotFound. The answer has the vlatte-error trailer either way.
func (*ConfigBuilder) NoNearMisses ¶
func (cb *ConfigBuilder) NoNearMisses() *ConfigBuilder
NoNearMisses turns off the report of the mocks closest to a call no mock matched: see Config.NoNearMisses.
func (*ConfigBuilder) OnCompleteListener ¶
func (cb *ConfigBuilder) OnCompleteListener(name string, listener vlatte.EventListener[vlatte.OnComplete]) *ConfigBuilder
OnCompleteListener registers listener under name, for the on_complete events of mocks that name it: see vlatte.EventConfig. It registers when the server is built, in the server's registry, or in the one EventListeners set: a name it has already fails New with vlatte.ErrEventAlreadyRegistered.
func (*ConfigBuilder) OutboundAllow ¶
func (cb *ConfigBuilder) OutboundAllow(prefixes ...netip.Prefix) *ConfigBuilder
OutboundAllow adds the ranges the server may connect to: once set, it refuses every other address. See Config.OutboundAllow.
func (*ConfigBuilder) OutboundDeny ¶
func (cb *ConfigBuilder) OutboundDeny(prefixes ...netip.Prefix) *ConfigBuilder
OutboundDeny adds ranges the server refuses to connect to, such as 169.254.0.0/16. See Config.OutboundAllow.
func (*ConfigBuilder) Record ¶
func (cb *ConfigBuilder) Record(options ...RecordConfigurer) *ConfigBuilder
Record records the calls the server proxies, from Start to Close, with the default settings, which options change: see RecordConfig.
func (*ConfigBuilder) Reflection ¶
func (cb *ConfigBuilder) Reflection() *ConfigBuilder
Reflection serves the gRPC server reflection service, so tools such as grpcurl and Postman list the services the server serves, and describe their messages: those registered on it, those of its descriptors, and those its mocks name.
func (*ConfigBuilder) RootDir ¶
func (cb *ConfigBuilder) RootDir(dir string) *ConfigBuilder
RootDir sets where relative MockFiles patterns start. The default is the working directory.
func (*ConfigBuilder) ServerOptions ¶
func (cb *ConfigBuilder) ServerOptions(options ...grpc.ServerOption) *ConfigBuilder
ServerOptions adds options of the gRPC server, such as interceptors, which run before the mocks. With a journal, a stream interceptor goes through grpc.ChainStreamInterceptor, not grpc.StreamInterceptor, which the journal takes: New fails with ErrStreamInterceptorSlot.
func (*ConfigBuilder) Service ¶
func (cb *ConfigBuilder) Service(sd *grpc.ServiceDesc, impl any) *ConfigBuilder
Service registers impl as the implementation of the service sd describes, as RegisterService does. The mocks answer its calls: a service needs no registration to be mocked, so this is for the services whose generated code the program doesn't otherwise have registered.
func (*ConfigBuilder) ShutdownTimeout ¶
func (cb *ConfigBuilder) ShutdownTimeout(d time.Duration) *ConfigBuilder
ShutdownTimeout sets how long Close waits for the calls in flight, such as a stream a client never ends, before it cuts them. The default is 5s.
func (*ConfigBuilder) Silent ¶
func (cb *ConfigBuilder) Silent() *ConfigBuilder
Silent turns off the logs of the logger the server builds.
func (*ConfigBuilder) TLSCertKeyPair ¶
func (cb *ConfigBuilder) TLSCertKeyPair(certFile, keyFile string) *ConfigBuilder
TLSCertKeyPair sets the certificate Server.StartTLS serves, from the PEM files of the certificate and its key. New fails on a file it can't load. Without a certificate, StartTLS serves a self-signed one.
func (*ConfigBuilder) TLSCertificates ¶
func (cb *ConfigBuilder) TLSCertificates(certs []tls.Certificate) *ConfigBuilder
TLSCertificates sets the certificates Server.StartTLS serves.
func (*ConfigBuilder) TLSClientCAs ¶
func (cb *ConfigBuilder) TLSClientCAs(pool *x509.CertPool) *ConfigBuilder
TLSClientCAs sets the CAs that client certificates must be signed by: Server.StartTLS then requires one (mutual TLS).
func (*ConfigBuilder) TLSConfig ¶
func (cb *ConfigBuilder) TLSConfig(c *tls.Config) *ConfigBuilder
TLSConfig sets the TLS configuration Server.StartTLS serves, in place of the one TLSCertKeyPair, TLSMutual, TLSCertificates and TLSClientCAs make.
func (*ConfigBuilder) TLSMutual ¶
func (cb *ConfigBuilder) TLSMutual(certFile, keyFile, clientCAFile string) *ConfigBuilder
TLSMutual sets the certificate Server.StartTLS serves, as TLSCertKeyPair does, and requires clients to present a certificate signed by a CA of the PEM file clientCAFile (mutual TLS). Empty clientCAFile requires none.
func (*ConfigBuilder) TemplateDataProviders ¶
func (cb *ConfigBuilder) TemplateDataProviders(providers ...TemplateDataProvider) *ConfigBuilder
TemplateDataProviders sets the providers of data templates read as .Provided.<Key>: see TemplateDataProvider.
func (*ConfigBuilder) TemplateEngine ¶
func (cb *ConfigBuilder) TemplateEngine(e vlatte.TemplateEngine) *ConfigBuilder
TemplateEngine sets the engine that compiles the templates of replies and events. The default is a vlatte.GoTemplateEngine.
func (*ConfigBuilder) TemplateEnv ¶
func (cb *ConfigBuilder) TemplateEnv(names ...string) *ConfigBuilder
TemplateEnv allows the templates of the server's default engine to read the environment variables names with env. See Config.TemplateEnv.
func (*ConfigBuilder) TemplateKeys ¶
func (cb *ConfigBuilder) TemplateKeys(specs ...string) *ConfigBuilder
TemplateKeys sets the keys the templates of the server's default engine sign and publish with: see Config.TemplateKeys.
type ConfigFlag ¶
ConfigFlag describes the command-line flag of a setting.
func ConfigFlags ¶
func ConfigFlags() []ConfigFlag
ConfigFlags describes the command-line flag of every server setting, for example to register shell completions.
type ConfigSource ¶
ConfigSource is a source of server settings, such as a file, the environment or arguments.
func ConfigArgs ¶
func ConfigArgs(args []string) ConfigSource
ConfigArgs reads server settings from command-line arguments, such as --grpc-addr=:50051. Every argument must be one of them: the vlatte command splits its arguments between its servers by their flags, see ConfigFlags.
func ConfigEnv ¶
func ConfigEnv() ConfigSource
ConfigEnv reads server settings from VLATTE_GRPC_* environment variables, such as VLATTE_GRPC_ADDR for grpc.addr, and VLATTE_CONFIG. The other VLATTE_* variables are the HTTP server's: a VLATTE_GRPC_* variable that is no setting is an error.
func ConfigFile ¶
func ConfigFile(path string, dirs ...string) ConfigSource
ConfigFile reads server settings from a JSON or YAML file: those of its grpc section. With dirs, path is a base name, such as DefaultConfigFileName, looked up in each dir; finding none is fine. A --config flag or VLATTE_CONFIG variable from a later source names the file to read instead.
func DefaultConfigSources ¶
func DefaultConfigSources(args []string) []ConfigSource
DefaultConfigSources lists the sources a server reads when Config.ConfigSources is nil, lowest precedence first: the config file, VLATTE_GRPC_* environment variables, then args.
type EchoReply ¶
type EchoReply struct {
// contains filtered or unexported fields
}
EchoReply answers each call with the messages the client sent, as they came: each one's bytes, read as a message of the type the method answers with, so the fields of the same numbers come back. A unary or server streaming call answers its request, a bidi streaming call each message as it comes, and a client streaming call the last message the client sent, or an empty one when it sent none. A message whose bytes don't read as the output type, such as bytes that aren't UTF-8 for a text field, fails the call.
func Echo ¶
func Echo() *EchoReply
Echo creates a new EchoReply. Mock files have no echo reply: describing a mock with it fails, so the admin API can't show the mock, nor save it.
func (*EchoReply) Log ¶
Log logs each message the reply echoes, with the server's logger, at info level.
func (*EchoReply) NewReplier ¶
func (e *EchoReply) NewReplier(app *Server, _ []protoreflect.MethodDescriptor) (Replier, error)
NewReplier implements Reply.
type JournalConfig ¶
type JournalConfig struct {
// Dir is where the journal keeps its files, across restarts. Empty keeps them in a temporary directory, which
// Close removes.
Dir string
// MaxEntries is how many calls the journal keeps, the newest. 0 keeps them all.
MaxEntries int
// MaxBodySize is how many bytes of a call's request message, as JSON, the journal keeps. 0 keeps whole messages.
MaxBodySize int64
}
JournalConfig configures the journal of a server: the calls its mocks get, of every outcome, which tests and the admin API verify and search, while the server runs: Close closes it. The calls an interceptor of ServerOptions answers aren't in it. An entry has the code the client gets, after every interceptor of ServerOptions: a stream interceptor goes through grpc.ChainStreamInterceptor then, see ErrStreamInterceptorSlot.
type KVView ¶
KVView gives templates the server's key-value store as text: {{ .KV.Get "key" }}. A key that may be missing reads with Has first: {{ if .KV.Has "key" }}.
type Kit ¶
type Kit struct {
// contains filtered or unexported fields
}
Kit is the vlatte.Kit of gRPC mocks: the server's template engine, logger and webhook transport, the template data of the call, and the directory of the mock file of the event it serves.
func (*Kit) Dir ¶
Dir implements vlatte.Kit: the directory of the mock file that defines the event, or "" for the working directory, as for events defined in Go and global events.
func (*Kit) TemplateEngine ¶
func (k *Kit) TemplateEngine() vlatte.TemplateEngine
TemplateEngine implements vlatte.Kit.
func (*Kit) Transport ¶
func (k *Kit) Transport() http.RoundTripper
Transport implements vlatte.Kit: a transport the server makes and closes with it.
type MatcherSpec ¶
type MatcherSpec []any
MatcherSpec is a matcher as mock files write it, such as ["equal", "a"] or ["not", "present"].
type Mock ¶
type Mock struct {
// contains filtered or unexported fields
}
Mock is a mock of a gRPC method, which a Builder builds.
func DecodeMock ¶
DecodeMock builds the mock data describes in format, as EncodeMock wrote it, for the server app, as a mock the admin API added: a reset of the server removes it, unless its store holds it still. Its relative body files open from the working directory. When data has problems, the error lists each.
func (*Mock) Close ¶
Close releases what the mock's replier holds, such as the connection of a proxy to its target. The store closes a mock when it leaves the server, and Server.Close closes the mocks still stored. Only the first call does anything.
func (*Mock) Describe ¶
func (m *Mock) Describe() vlatte.Descriptor
Describe implements vlatte.SelfDescriptive: the mock as a mock file writes it, which the admin API returns and saves. A mock read from a document is described by it, with its ID. A mock built in Go is described whole, or not at all: a part no mock file can hold, such as a Func, Echo or Shared reply, a CallMatches matcher, a matcher that doesn't describe itself, a callback or a vlatte.DelayFunc delay, fails encoding the description, with an error that names it, so the admin API never shows a mock that loads back matching more calls, answering differently or without its callbacks. RandWith's generator is the exception: a mock file loads it back as a Rand, which picks from the same replies.
func (*Mock) Events ¶
Events returns the events the mock runs once it replied, its callbacks included.
func (*Mock) Hits ¶
Hits returns how many calls the mock answered, with messages or with a status, and is answering.
func (*Mock) Origin ¶
Origin returns where the mock comes from, such as the mock file that describes it, or "" for a mock built in Go.
type OnComplete ¶
type OnComplete struct {
// contains filtered or unexported fields
}
OnComplete implements vlatte.OnComplete for gRPC mocks. Listeners, and the callbacks of Builder.Callback, get it once the mock replied, and the call ends after them, but for those set to run after the response, which mustn't call Call.Send or Call.Recv: the call ended. It's read-only: the listeners of a call run at the same time. Listeners use the context they get: the client leaving doesn't end it, as it ends the call's.
func (*OnComplete) Call ¶
func (i *OnComplete) Call() *Call
Call returns the call the mock answered: its request, and the messages the mock sent, in Call.Sent.
func (*OnComplete) Dir ¶
func (i *OnComplete) Dir() string
Dir is where relative files of the event's parameters open from: the directory of the mock file that defines the event, or "" for the working directory, as for events defined in Go and global events.
func (*OnComplete) Logger ¶
func (i *OnComplete) Logger() *zerolog.Logger
Logger is the server's logger, so listeners such as webhooks log where the server does, and as little.
func (*OnComplete) Mock ¶
func (i *OnComplete) Mock() vlatte.Mock
Mock implements vlatte.OnComplete: the mock that answered the call.
func (*OnComplete) Parameters ¶
func (i *OnComplete) Parameters() vlatte.Parameters
Parameters implements vlatte.EventArgs: the parameters of the event, as its listener prepared them.
func (*OnComplete) Status ¶
func (i *OnComplete) Status() *status.Status
Status returns the status the mock ended the call with: OK, or the status of its reply.
type Option ¶
type Option = vlatte.Configurer[*Config]
Option configures a Server. Both Config and ConfigBuilder are options.
type ProxyReply ¶
type ProxyReply struct {
// contains filtered or unexported fields
}
ProxyReply answers each call with the answer of another gRPC server, the target: the mock sends it the call, its metadata and messages, and sends the client the target's header, messages, trailer and status, as they come. It serves every call type: a bidi call goes on message by message, in both directions. Use From to make one. Each mock built with it gets a connection of its own, which closes when the mock leaves the server, or the server closes.
A status of the target's is the mock's answer, as a status of Status's is. A target the mock can't reach fails the call: the client gets Internal with the vlatte-error trailer.
func From ¶
func From(target string) *ProxyReply
From returns a ProxyReply to target, a gRPC target such as localhost:50051 or dns:///api.example.com:443, as grpc.NewClient takes it. It connects without TLS: see ProxyReply.DialOptions.
func (*ProxyReply) DialOptions ¶
func (r *ProxyReply) DialOptions(opts ...grpc.DialOption) *ProxyReply
DialOptions sets options of the connection to the target, after the reply's own, which connects without TLS: such as grpc.WithTransportCredentials for a target that serves TLS. A mock file can't hold them: describing a mock with them fails, so the admin API can't show the mock, nor save it.
func (*ProxyReply) Header ¶
func (r *ProxyReply) Header(key string, values ...string) *ProxyReply
Header adds metadata the target gets, which replaces the client's values of that key: a token for the target in place of the client's.
func (*ProxyReply) NewReplier ¶
func (r *ProxyReply) NewReplier(app *Server, _ []protoreflect.MethodDescriptor) (Replier, error)
NewReplier implements Reply. It makes the connection of the mock, which connects on its first call.
func (*ProxyReply) RemoveHeaders ¶
func (r *ProxyReply) RemoveHeaders(keys ...string) *ProxyReply
RemoveHeaders removes the client's metadata of those keys from what the target gets.
type RandomReply ¶
type RandomReply struct {
// contains filtered or unexported fields
}
RandomReply answers each call of a mock with one of its replies, picked at random. A call of any type takes one reply, a stream as a whole. Each mock built with it picks from replies of its own.
func RandWith ¶
func RandWith(random *rand.Rand, reply ...Reply) *RandomReply
RandWith creates a new RandomReply that picks replies with random. Every mock built with the reply picks with it. A mock with it is described without its generator: a mock file loads it back as a Rand.
func RandWithSeed ¶
func RandWithSeed(seed int64, reply ...Reply) *RandomReply
RandWithSeed creates a new RandomReply that picks replies in an order the seed repeats. Each mock built with the reply picks with a generator of its own, from the seed, so each one picks in the same order.
func (*RandomReply) Add ¶
func (rep *RandomReply) Add(reply ...Reply) *RandomReply
Add adds replies to pick from.
func (*RandomReply) NewReplier ¶
func (rep *RandomReply) NewReplier(app *Server, methods []protoreflect.MethodDescriptor) (Replier, error)
NewReplier implements Reply. It makes the replier of each reply, which checks itself against the methods, so each mock picks from replies of its own.
type Recipe ¶
Recipe prepares a Server, for example by adding a set of mocks; see Server.Prep.
type RecordConfig ¶
type RecordConfig struct {
// Dir is the directory of the recordings. Relative paths start at Config.RootDir. Defaults to _mocks_recorded.
Dir string
// Format is the format of the recorded mock files: json, yaml or yml. Defaults to json.
Format string
// Target is the server to record, as grpc.NewClient takes it, such as localhost:50051: the calls the recording
// takes go to it, before any mock, and its answers are recorded. Without one, the recording takes what the mocks
// that proxy answer, such as From's.
Target string
// DialOptions are options of the connection to the Target, after the recording's own, which connects without TLS:
// such as grpc.WithTransportCredentials for a target that serves TLS.
DialOptions []grpc.DialOption
// Methods name the methods of the calls the recording takes, by whole segments of their full method, as Method
// names them: Method, Service/Method, pkg.Service/Method or /pkg.Service/Method. None takes every method.
Methods []string
// RequestHeaders are the metadata keys a recording matches: the value each had, or its absence. A recording matches
// no other metadata.
RequestHeaders []string
// Repeats is what a recording keeps of a request that comes again: every answer, in order, or the first one.
// Defaults to vlatte.RecordSequence.
Repeats vlatte.RecordRepeats
// IncludeMocked records the answers of mocks too. Without it, only proxied answers are recorded: those of the
// Target and of proxy replies, such as From.
IncludeMocked bool
// Transforms change each recording before it is written, in order. A transform that fails skips the recording,
// and so do transforms that leave it no response.
Transforms []func(*RecordedMock) error
}
RecordConfig configures recording: where the recordings go, and what they match. See Server.StartRecording.
A recording writes a mock file for each request: a call of the same method, with the same messages and the metadata RequestHeaders names. It answers the way the calls of that request were answered, in turn, then the way the last one was, as Repeats sets: its header, its messages, its trailer and its status. A bidi call matches on its method and metadata only, as bidi mocks do, and plays its messages back at once, without waiting for the client's.
func (*RecordConfig) Apply ¶
func (r *RecordConfig) Apply(c *RecordConfig) error
Apply sets the fields of r that aren't zero on c, and adds r's DialOptions and Transforms to c's, so configs compose. A config turns no setting off: options such as RecordIncludeMocked(false) do.
type RecordConfigurer ¶
type RecordConfigurer interface {
Apply(c *RecordConfig) error
}
RecordConfigurer lets users configure recording.
func RecordDialOptions ¶
func RecordDialOptions(opts ...grpc.DialOption) RecordConfigurer
RecordDialOptions adds options of the connection to the target. See RecordConfig.DialOptions.
func RecordDir ¶
func RecordDir(dir string) RecordConfigurer
RecordDir sets the directory of the recordings. Relative paths start at Config.RootDir.
func RecordFormat ¶
func RecordFormat(format string) RecordConfigurer
RecordFormat sets the format of the recorded mock files: json, yaml or yml.
func RecordIncludeMocked ¶
func RecordIncludeMocked(v bool) RecordConfigurer
RecordIncludeMocked sets whether the answers of mocks are recorded too, not only proxied ones.
func RecordMethods ¶
func RecordMethods(methods ...string) RecordConfigurer
RecordMethods sets the methods of the calls the recording takes. See RecordConfig.Methods.
func RecordRepeats ¶
func RecordRepeats(repeats vlatte.RecordRepeats) RecordConfigurer
RecordRepeats sets what a recording keeps of a request that comes again: vlatte.RecordSequence, the default, or vlatte.RecordFirst.
func RecordRequestHeaders ¶
func RecordRequestHeaders(keys ...string) RecordConfigurer
RecordRequestHeaders sets the metadata keys recordings match: the value each had, or its absence.
func RecordTarget ¶
func RecordTarget(target string) RecordConfigurer
RecordTarget sets the server to record. See RecordConfig.Target.
func RecordTransform ¶
func RecordTransform(transform func(*RecordedMock) error) RecordConfigurer
RecordTransform adds a transform, which changes each recording before it is written. A transform that fails skips the recording.
type RecordedMock ¶
type RecordedMock = vlatte.RecordedMock[RecordedRequest, RecordedResponse]
RecordedMock is a mock a recording made, as RecordConfig.Transforms change it; see vlatte.RecordedMock.
type RecordedRequest ¶
type RecordedRequest struct {
// Method is the full method, such as /pkg.Service/Method.
Method string `json:"method"`
// Header matches the metadata RecordConfig.RequestHeaders names.
Header map[string]MatcherSpec `json:"header,omitempty"`
// Message is the request of a unary or server streaming call.
Message any `json:"message,omitzero"`
// Messages are the requests of a client streaming call, in order. A bidi call matches no message.
Messages []any `json:"messages,omitzero"`
}
RecordedRequest is what a recording matches: the request section of its mock file. A message is written as protojson writes it, with the field names of the .proto file, decoded as JSON, such as a map[string]any.
type RecordedResponse ¶
type RecordedResponse struct {
Header map[string][]string `json:"header,omitempty"`
Trailer map[string][]string `json:"trailer,omitempty"`
// Message is the answer of a unary or client streaming call that ended with OK.
Message any `json:"message,omitzero"`
// Messages are the answers of a server or bidi streaming call, in order.
Messages []any `json:"messages,omitempty"`
// Status is the status the call ended with, unless OK.
Status *RecordedStatus `json:"status,omitzero"`
}
RecordedResponse is the answer a recording replies with: the response section of its mock file.
type RecordedStatus ¶
type RecordedStatus struct {
// Code is the name of the code, such as NOT_FOUND.
Code string `json:"code"`
Message string `json:"message,omitempty"`
// Details are the details of the status, each an Any as protojson writes it, with its "@type".
Details []any `json:"details,omitempty"`
}
RecordedStatus is the status a recorded call ended with.
type Replier ¶
Replier answers the calls of one mock. Reply sends the answer through call: the messages with Call.Send, and the header and trailer with grpc.SetHeader, grpc.SendHeader and grpc.SetTrailer on ctx. An error with a gRPC status, such as status.Error makes, ends the call with that status: it is the mock's answer.
An error that matches vlatte.ErrAbort or vlatte.ErrReset cuts the call, as a server that crashes would: the mock counts the call and runs its events, then the server cuts the call's connection after the messages of a stream Reply sent, before any status, so the client reads Unavailable and no trailer. ErrReset resets a TCP connection, so the client reads ECONNRESET, and ErrAbort ends it. grpc can't reset one stream from a handler, so the other calls on the connection end too. A server whose ServerOptions set grpc.Creds can't cut its connections: the call fails.
Any other error is a failure, which the client gets as Internal with the vlatte-error trailer.
type ReplierFunc ¶
ReplierFunc is a Replier of a function, and a Reply that gives every mock that function.
func Func ¶
func Func(fn func(ctx context.Context, call *Call) error) ReplierFunc
Func returns a Reply that answers each call with fn, which sends the answer through call: see Replier. A unary or client streaming call whose fn sends no message answers with an empty message of the method's output type. A mock file can't hold a function: describing a mock with it fails, so the admin API can't show the mock, nor save it.
func (ReplierFunc) NewReplier ¶
func (f ReplierFunc) NewReplier(*Server, []protoreflect.MethodDescriptor) (Replier, error)
NewReplier implements Reply.
type Reply ¶
type Reply interface {
NewReplier(app *Server, methods []protoreflect.MethodDescriptor) (Replier, error)
}
Reply is what a mock answers the calls it matches with: Message, Messages, JSON, Template, Status, Bidi, Seq, Rand, Echo, Shared and Func make one. Builder.Build asks it for a Replier for each mock, given the methods the mock serves, so it checks there what it can, such as that its messages are of the type the methods answer with.
func Shared ¶
Shared returns a Reply that gives r to every mock built with it: those mocks share r, and whatever it keeps. Use it for a Replier that keeps no state, such as one from another package. A Replier that keeps state, such as a counter, should come from a Reply of its own that makes one for each mock. The mocks never close r: when it implements io.Closer, closing it is the caller's. Mock files have no shared reply: describing a mock with it fails, so the admin API can't show the mock, nor save it.
type Response ¶
type Response struct {
// contains filtered or unexported fields
}
Response describes the answer of a mock: its messages, header, trailer and the status it ends with. It is a Reply: each mock built with it gets a replier of its own, so changing it after Mock changes only the mocks built afterwards. It keeps the messages it is given without copying them: don't change them afterwards.
A unary or client streaming method answers one message, or a status: the empty message of its output type when the Response has neither. A server or bidi streaming method answers each message in turn, then the status.
func JSON ¶
JSON returns a Response that answers the messages texts hold, each as protojson reads it, in the type the method answers with: {"message": "hi"}. Build fails on text that doesn't hold such a message.
func Message ¶
Message returns a Response that answers msg, which must be of the type the method answers with.
func Messages ¶
Messages returns a Response that answers msgs, in order: the messages of a server or bidi streaming answer.
Example ¶
package main
import (
"context"
"fmt"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/caffeine-projects/vlatte/mockgrpc"
pb "github.com/caffeine-projects/vlatte/mockgrpc/internal/protobuf"
)
func main() {
m := mockgrpc.MustNew(mockgrpc.Setup().Silent().InMemory())
m.MustStart()
defer m.Close()
// A server stream answers each message in turn, then ends with the status.
m.MustMock(mockgrpc.Method("TestService/List").
Reply(mockgrpc.Messages(&pb.ListItem{Key: "a"}, &pb.ListItem{Key: "b"}).Status(codes.Unavailable, "gone")))
stream, err := pb.NewTestServiceClient(m.MustDial()).List(context.Background(), &pb.ListReq{})
if err != nil {
panic(err)
}
for {
item, err := stream.Recv()
if err != nil {
fmt.Println(status.Code(err))
break
}
fmt.Println(item.GetKey())
}
}
Output: a b Unavailable
func Template ¶
Template returns a Response like JSON's, whose texts are templates of the server's template engine, rendered for each call with TemplateData: {"message": "hi {{ .Request.Message.name }}"}. A text that doesn't render a message of the type the method answers with fails the call.
func (*Response) Details ¶
Details adds details to the status the answer ends with, such as the errdetails messages clients read with status.Details: &errdetails.BadRequest{...}. They need a status other than OK.
func (*Response) Header ¶
Header adds metadata the answer starts with, sent before its first message. The last value of a key the server sets itself, such as the debug headers, goes with them.
func (*Response) MessageDelay ¶
MessageDelay chooses the wait before each message. Nil disables it. An evaluation error ends the reply.
func (*Response) NewReplier ¶
func (r *Response) NewReplier(app *Server, methods []protoreflect.MethodDescriptor) (Replier, error)
NewReplier implements Reply. It checks the Response against each method: that its messages are of the type the method answers with, and that a method that answers one message gets one, or a status.
type Scope ¶
Scope holds the mocks added by one Mock call; see vlatte.Scope.
type SequentialReply ¶
type SequentialReply struct {
// contains filtered or unexported fields
}
SequentialReply answers the calls of a mock with its replies, one per call, in order, then with the one set with OnSequenceEnded. A call of any type takes the next reply, a stream as a whole. Each mock built with it runs the sequence on its own, from the first reply. A call that comes once the sequence is over, without OnSequenceEnded, fails: the client gets Internal with the vlatte-error trailer.
func (*SequentialReply) Add ¶
func (r *SequentialReply) Add(reply ...Reply) *SequentialReply
Add adds replies to the sequence.
func (*SequentialReply) NewReplier ¶
func (r *SequentialReply) NewReplier(app *Server, methods []protoreflect.MethodDescriptor) (Replier, error)
NewReplier implements Reply. It makes the replier of each reply of the sequence, which checks itself against the methods, so each mock has replies and a place in the sequence of its own.
func (*SequentialReply) OnSequenceEnded ¶
func (r *SequentialReply) OnSequenceEnded(reply Reply) *SequentialReply
OnSequenceEnded sets the reply of the calls that come once the sequence is over.
type Server ¶
type Server struct {
*vlatte.Base[*Mock, *Server]
*verify.Verifier[*Mock, *Server]
// contains filtered or unexported fields
}
Server is a gRPC mock server. New creates it and Server.Start serves it, once: a closed server doesn't start again.
func New ¶
New creates a new gRPC mock Server with the given configurations. It returns an error if a configuration fails to apply.
func (*Server) Addr ¶
Addr returns the address the server listens on, or "" before it starts. An in-memory server's is "bufconn", which no network reaches: connect with Server.Dial.
func (*Server) AdminURL ¶
AdminURL returns the base URL of the admin API, or "" when the server serves none, or hasn't started: see ConfigBuilder.Admin.
func (*Server) Certificate ¶
func (app *Server) Certificate() *x509.Certificate
Certificate returns the certificate the server serves since StartTLS, for clients to trust, as crypto/x509.CertPool.AddCert does. It returns nil before StartTLS, after Start, for a Config.TLSConfig without certificates, such as one with GetCertificate, and for a server whose ServerOptions set grpc.Creds.
func (*Server) Close ¶
func (app *Server) Close()
Close stops the server, waiting for calls in flight to finish. It closes the admin API first, which waits for the operations it serves. It cancels the on_complete events still running, and waits for those that run after the response. It closes the idle connections of the transport it gives webhooks, and the journal last, which it removes if it is a temporary one: verify the calls before Close. A closed server doesn't start again, even one that never started.
func (*Server) Config ¶
Config returns the configuration of the server, as its options and sources left it. Changing it after New changes nothing the server set up already.
func (*Server) Data ¶
Data returns the data templates read as .Data. Calls read the map, so don't change it: set new data instead.
func (*Server) Dial ¶
func (app *Server) Dial(opts ...grpc.DialOption) (*grpc.ClientConn, error)
Dial returns a new client connection to the server, which Close closes: one per test, or per client of a test. It dials without TLS after Start, and with TLS after StartTLS, trusting the certificate the server serves: see Server.Certificate. It reaches an in-memory server too. opts come after its own, so they can change them, such as grpc.WithTransportCredentials for a server that requires a client certificate, or whose ServerOptions set TLS. It fails before Start, and after Close with grpc.ErrServerStopped.
func (*Server) GRPCServer ¶
GRPCServer returns the underlying gRPC server, for features beyond registering services, such as server reflection. With a journal, a service registered on it has the entries of its unary calls journaled within the interceptors of ServerOptions, with the code the mocks answered with: Server.Start warns of it. Server.RegisterService journals the code the client gets.
func (*Server) IsRecording ¶
IsRecording reports whether a recording takes calls.
func (*Server) KV ¶
KV returns the key-value store templates read as .KV: the one ConfigBuilder.KV set, or the memory store the server made without one, which Config.KV holds too.
func (*Server) MustDial ¶
func (app *Server) MustDial(opts ...grpc.DialOption) *grpc.ClientConn
MustDial is like Dial, but panics if it fails.
func (*Server) MustStart ¶
func (app *Server) MustStart()
MustStart starts the mock server. It fails immediately if any error occurs.
func (*Server) MustStartTLS ¶
func (app *Server) MustStartTLS()
MustStartTLS is like StartTLS, but panics if it fails.
func (*Server) Prep ¶
Prep runs the given recipes on this mock server, in order. It stops at the first recipe that fails and returns its error.
func (*Server) RecordingStatus ¶
func (app *Server) RecordingStatus() vlatte.RecordStatus
RecordingStatus counts the calls of the recording, or returns a zero status when there is none.
func (*Server) RegisterService ¶
func (app *Server) RegisterService(desc *grpc.ServiceDesc, impl any)
RegisterService registers a service on the mock server, so generated code can take it directly:
pb.RegisterGreeterServer(m, pb.UnimplementedGreeterServer{})
It implements grpc.ServiceRegistrar and must be called before Start. With a journal, the entries of its calls have the code the client gets, after every interceptor: register services here, not on Server.GRPCServer.
func (*Server) Reload ¶
Reload loads the mock files of Config.MockFiles again, and the mocks of the admin API's persistent store, if any: edited and removed files take effect, and changes made to the store directly, in one step. When a file or the store has problems, Reload changes nothing.
func (*Server) RequestPattern ¶
RequestPattern returns the pattern of journal entries that the request part of b matches, as it matches a call: b is a *Builder, such as Method("Greetings").Field("message", match.Equal("hi")), whose reply counts for nothing. Times, Once and scenarios match no call served before, so a pattern has none. It implements verify.Patterns, for VerifyRequests().Matching.
func (*Server) ResetScenario ¶
func (app *Server) ResetScenario(name string, in ...matchscenario.Instance)
ResetScenario moves the scenario name back to matchscenario.StateStarted: every instance of it, or only the one of a key in, such as matchscenario.Key("t1"). An instance nothing moved and none set is there already: the admin API's events get no move of it.
func (*Server) ResetScenarios ¶
func (app *Server) ResetScenarios()
ResetScenarios moves every scenario back to matchscenario.StateStarted.
func (*Server) Scenarios ¶
Scenarios returns every scenario, by name: those the server's mocks name, with their states and the moves of their mocks, and those set without a mock. A disabled mock counts, as it matches again once enabled.
func (*Server) SetData ¶
SetData sets the data templates read as .Data, such as the address of another server: {{ .Data.target }}. The server keeps a copy of the map, and calls read the data in force when they arrive.
func (*Server) SetScenario ¶
func (app *Server) SetScenario(ctx context.Context, name, state string, in ...matchscenario.Instance) error
SetScenario moves the scenario name to state: its shared instance, or the one of a key in, such as matchscenario.Key("t1"). The mocks that require state match next. It returns an error that wraps matchscenario.ErrUnknownState when no mock of the scenario names state, or state is empty. A scenario no mock names moves to any other state.
func (*Server) Start ¶
Start starts the mock server. A server starts once: Start fails with vlatte.ErrStarted once it started, and with grpc.ErrServerStopped once it closed. Start is all or nothing: it serves once it listens and its admin API, if any, serves. A start that fails stops what started, closes the server, and leaves nothing listening, the listener of Config.Listener included.
func (*Server) StartRecording ¶
func (app *Server) StartRecording(options ...RecordConfigurer) error
StartRecording starts recording what the server proxies as mock files, which answer the same calls the same way: see RecordConfig. It starts from the server's record settings, or the defaults, which options change. It returns vlatte.ErrRecording while another recording runs, or still writes what it took.
func (*Server) StartTLS ¶
StartTLS starts the mock server as Start does, serving TLS: Config.TLSConfig, or the certificates of Config.TLSCertificates, requiring a client certificate when Config.TLSClientCAs is set. Without either, it serves a self-signed certificate for localhost, 127.0.0.1 and ::1, valid for a day: see Certificate. Dial trusts the certificate the server serves. Credentials that ServerOptions set with grpc.Creds win over all of these: the server serves them as Start does, Certificate returns nil, and Dial dials as it does after Start, so pass it grpc.WithTransportCredentials.
func (*Server) StopRecording ¶
StopRecording stops the recording, waits until it wrote what it took, and returns what it wrote. The server then serves the recordings: its mock files load again, with the recording's directory, so the hits of file mocks count from 0. When ctx ends first, it returns ctx's error, and the recording goes on writing: a later StopRecording waits again, and a StartRecording once it wrote everything ends it. Either serves it. It returns vlatte.ErrNotRecording when there is no recording. The error joins the calls and mocks that couldn't be recorded, and why the recordings aren't served, such as a mock ID they share with a mock file, or the server closing first.
type TemplateData ¶
type TemplateData struct {
// Request is the call being served.
Request *TemplateRequest
// KV reads the server's key-value store: {{ .KV.Get "key" }}.
KV *KVView
// Scenarios reads the state of the server's scenarios: {{ .Scenarios.State "checkout" }}, and of the instance of
// a key, {{ .Scenarios.StateOf "checkout" (index .Request.Header "x-test-id" 0) }}. A scenario the mock that matched
// moved is in the state it moved it to, even once another request moved it on.
Scenarios matchscenario.View
// Data is the data set with Server.SetData, in force when the call arrived: {{ .Data.target }}.
Data map[string]any
// Provided is what the server's template data providers gave for the call, by their key: {{ .Provided.user.name }}.
Provided map[string]any
}
TemplateData is what templates render with: the dot of the templates of Template replies, and the data of the Kit of event listeners, such as webhooks.
type TemplateDataProvider ¶
type TemplateDataProvider = vlatte.TemplateDataProvider[*TemplateDataProviderInput]
TemplateDataProvider adds data to the templates of gRPC mocks, which read it as .Provided.<Key>. The server calls Data once for each call a mock matched, before the mock waits and replies: an error fails the call, with the vlatte-error trailer.
type TemplateDataProviderInput ¶
type TemplateDataProviderInput struct {
// contains filtered or unexported fields
}
TemplateDataProviderInput is what a TemplateDataProvider receives for each call.
func (*TemplateDataProviderInput) Call ¶
func (in *TemplateDataProviderInput) Call() *Call
Call returns the call being served.
func (*TemplateDataProviderInput) Mock ¶
func (in *TemplateDataProviderInput) Mock() *Mock
Mock returns the mock that matched the call.
type TemplateRequest ¶
type TemplateRequest struct {
// Method is the full method of the call: /pkg.Service/Method.
Method string
// Header is the metadata the client sent: {{ index .Request.Header "x-team" 0 }}.
Header metadata.MD
// Message is the request message as JSON reads it, field by field, with the field names of the .proto file:
// {{ .Request.Message.user_id }}. A client streaming call has the array of its messages: {{ index
// .Request.Message 0 }}.
Message any
}
TemplateRequest is the call being served, to templates.
Source Files
¶
- admin.go
- admin_store.go
- alias.go
- bidi.go
- call.go
- config.go
- config_schema.go
- conn.go
- cut.go
- doc.go
- grpc.go
- journal.go
- loader.go
- method.go
- mock.go
- mock_builder.go
- mock_builder_fs.go
- mock_describe.go
- mock_schema.go
- oncomplete.go
- record_codec.go
- record_config.go
- recording.go
- recover.go
- reflection.go
- reply.go
- reply_echo.go
- reply_proxy.go
- reply_random.go
- reply_seq.go
- reply_shared.go
- resolver.go
- response.go
- scenario.go
- serve.go
- server_stream.go
- template.go
- tls.go
- unary.go