Documentation
¶
Overview ¶
Package mockhttp runs HTTP mock servers for tests.
Start a Server, add mocks built with Get, Post and the other builders, and point the code under test at Server.URL:
m := mockhttp.MustNew()
m.MustStart()
defer m.Close()
m.MustMock(mockhttp.Getf("/hello").Reply(mockhttp.OK().PlainText("hello world")))
Use github.com/caffeine-projects/vlatte/match to match headers, query parameters or bodies. Builder.FormField and Builder.FormFile match the fields and files of forms, as net/http parses them, and Reply.Multipart replies with multipart bodies, streamed part by part when parts have delays. Mocks can also come from YAML or JSON files; see FromFile and ConfigBuilder.MockFilePatterns.
Settings come from code, then from a .vlatterc.json, .vlatterc.yaml or .vlatterc.yml file and VLATTE_* environment variables, each overriding the one before. ConfigBuilder.ConfigSources picks the sources, and ConfigUsage lists every setting.
Example ¶
package main
import (
"fmt"
"io"
"net/http"
"github.com/caffeine-projects/vlatte/mockhttp"
)
func main() {
m := mockhttp.MustNew(mockhttp.Setup().Silent())
m.MustStart()
defer m.Close()
scoped := m.MustMock(mockhttp.Getf("/hello").Reply(mockhttp.OK().PlainText("hello world")))
res, err := http.Get(m.URL("/hello"))
if err != nil {
panic(err)
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
panic(err)
}
fmt.Println(res.StatusCode, string(body), scoped.Called())
}
Output: 200 hello world true
Example (Multipart) ¶
package main
import (
"bytes"
"fmt"
"io"
"net/http"
"github.com/caffeine-projects/vlatte/match"
"github.com/caffeine-projects/vlatte/mockhttp"
)
func main() {
m := mockhttp.MustNew(mockhttp.Setup().Silent())
m.MustStart()
defer m.Close()
// Match an upload by its fields and files, and reply with a multipart body.
m.MustMock(mockhttp.Postf("/upload").
FormField("title", match.Equal("Holiday")).
FormFile("photo", mockhttp.FileWith().Filename(match.HasSuffix(".png"))).
Reply(mockhttp.Created().Multipart(mockhttp.MultipartMixed(
mockhttp.NewPart().ContentType("text/plain").BodyText("saved"),
).Boundary("b"))))
// A Multipart writes request bodies too.
contentType, body, err := mockhttp.MultipartForm(
mockhttp.NewPart().Name("title").BodyText("Holiday"),
mockhttp.NewPart().Name("photo").Filename("me.png").Body([]byte("PNG")),
).Encode(nil, nil)
if err != nil {
panic(err)
}
res, err := http.Post(m.URL("/upload"), contentType, bytes.NewReader(body))
if err != nil {
panic(err)
}
defer res.Body.Close()
reply, err := io.ReadAll(res.Body)
if err != nil {
panic(err)
}
fmt.Println(res.StatusCode, res.Header.Get(mockhttp.HeaderContentType))
fmt.Printf("%q\n", reply)
}
Output: 201 multipart/mixed; boundary=b "--b\r\nContent-Type: text/plain\r\n\r\nsaved\r\n--b--\r\n"
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 Backend
- type BackendConfig
- type BackendFactory
- type BackendInfo
- type Builder
- func AnyMethod() *Builder
- func Delete(m vlatte.Matcher) *Builder
- func Deletef(path string, a ...any) *Builder
- func Get(m vlatte.Matcher) *Builder
- func Getf(path string, a ...any) *Builder
- func Head(m vlatte.Matcher) *Builder
- func Headf(path string, a ...any) *Builder
- func Patch(u vlatte.Matcher) *Builder
- func Patchf(path string, a ...any) *Builder
- func Post(m vlatte.Matcher) *Builder
- func Postf(path string, a ...any) *Builder
- func ProxyAll(reply *ProxyReply) *Builder
- func Put(m vlatte.Matcher) *Builder
- func Putf(path string, a ...any) *Builder
- func Request() *Builder
- func (b *Builder) BasicAuth(username, password string) *Builder
- func (b *Builder) BasicAuthMatches(username, password vlatte.Matcher) *Builder
- func (b *Builder) Body(matcherList ...vlatte.Matcher) *Builder
- func (b *Builder) Build(app *Server) (*Mock, error)
- func (b *Builder) Callback(fn vlatte.EventFunc[vlatte.OnComplete]) *Builder
- func (b *Builder) ClientIP(m vlatte.Matcher) *Builder
- func (b *Builder) ContentType(value string, a ...any) *Builder
- func (b *Builder) Cookie(name string, m vlatte.Matcher) *Builder
- func (b *Builder) Delay(duration time.Duration) *Builder
- func (b *Builder) DelayFunc(delay vlatte.Delay) *Builder
- func (b *Builder) Enabled(enabled bool) *Builder
- func (b *Builder) FormField(name string, m vlatte.Matcher) *Builder
- func (b *Builder) FormFieldf(field string, value string, a ...any) *Builder
- func (b *Builder) FormFields(name string, m vlatte.Matcher) *Builder
- func (b *Builder) FormFile(name string, p *FilePattern) *Builder
- func (b *Builder) Header(name string, m vlatte.Matcher) *Builder
- func (b *Builder) Headerf(name string, value string, a ...any) *Builder
- func (b *Builder) Headers(name string, m vlatte.Matcher) *Builder
- func (b *Builder) Host(m vlatte.Matcher) *Builder
- func (b *Builder) ID(id string) *Builder
- func (b *Builder) Map(mapper Mapper) *Builder
- func (b *Builder) Matches(m vlatte.Matcher) *Builder
- func (b *Builder) Method(methods ...string) *Builder
- func (b *Builder) MethodMatches(m vlatte.Matcher) *Builder
- func (b *Builder) Name(name string) *Builder
- func (b *Builder) OnCompleteEvent(cfg vlatte.EventConfig) *Builder
- func (b *Builder) Once() *Builder
- func (b *Builder) PathParam(name string, m vlatte.Matcher) *Builder
- func (b *Builder) Priority(p int) *Builder
- func (b *Builder) Queries(name string, m vlatte.Matcher) *Builder
- func (b *Builder) Query(name string, m vlatte.Matcher) *Builder
- func (b *Builder) Queryf(name string, value string, a ...any) *Builder
- func (b *Builder) Reply(f ReplierFactory) *Builder
- func (b *Builder) RequestMatches(predicate func(r *http.Request) (bool, error)) *Builder
- func (b *Builder) RequestURI(uri string) *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) Scheme(scheme string) *Builder
- func (b *Builder) SchemeMatches(m vlatte.Matcher) *Builder
- func (b *Builder) SetSource(src string) *Builder
- func (b *Builder) StartScenario(name string) *Builder
- func (b *Builder) Step(steps ...vlatte.Step) *Builder
- func (b *Builder) Times(times int64) *Builder
- func (b *Builder) URL(m vlatte.Matcher) *Builder
- func (b *Builder) URLFragment(m vlatte.Matcher) *Builder
- func (b *Builder) URLFragmentf(format string, a ...any) *Builder
- func (b *Builder) URLPath(m vlatte.Matcher) *Builder
- func (b *Builder) URLPathTemplate(template string) *Builder
- func (b *Builder) URLPathf(format string, a ...any) *Builder
- func (b *Builder) URLf(format string, a ...any) *Builder
- func (b *Builder) UpstreamStep(steps ...vlatte.Step) *Builder
- func (b *Builder) WireStep(steps ...vlatte.Step) *Builder
- type CORSConfig
- type CORSConfigBuilder
- func (b *CORSConfigBuilder) AllowCredentials(allow bool) *CORSConfigBuilder
- func (b *CORSConfigBuilder) AllowMethods(methods ...string) *CORSConfigBuilder
- func (b *CORSConfigBuilder) AllowOrigin(origin ...string) *CORSConfigBuilder
- func (b *CORSConfigBuilder) AllowedHeaders(headers ...string) *CORSConfigBuilder
- func (b *CORSConfigBuilder) Apply(opts *CORSConfig)
- func (b *CORSConfigBuilder) ExposeHeaders(headers ...string) *CORSConfigBuilder
- func (b *CORSConfigBuilder) MaxAge(maxAge int) *CORSConfigBuilder
- func (b *CORSConfigBuilder) SuccessStatusCode(code int) *CORSConfigBuilder
- type CORSConfigurer
- 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) BackendFactory(factory BackendFactory) *ConfigBuilder
- func (cb *ConfigBuilder) CORS(options ...CORSConfigurer) *ConfigBuilder
- func (cb *ConfigBuilder) Colors(v bool) *ConfigBuilder
- func (cb *ConfigBuilder) ConfigSources(sources ...ConfigSource) *ConfigBuilder
- func (cb *ConfigBuilder) DebugFn(dfn DebugFn) *ConfigBuilder
- func (cb *ConfigBuilder) ErrorStatusCode(code int) *ConfigBuilder
- func (cb *ConfigBuilder) EventListeners(listeners *vlatte.Listener) *ConfigBuilder
- func (cb *ConfigBuilder) GlobalEvents(events *vlatte.Events) *ConfigBuilder
- func (cb *ConfigBuilder) HandlerDecorator(fn func(handler http.Handler) http.Handler) *ConfigBuilder
- func (cb *ConfigBuilder) Journal(dir string) *ConfigBuilder
- func (cb *ConfigBuilder) Listener(l net.Listener) *ConfigBuilder
- func (cb *ConfigBuilder) Loader(loader Loader) *ConfigBuilder
- func (cb *ConfigBuilder) LogBodyMaxSize(size int64) *ConfigBuilder
- func (cb *ConfigBuilder) LogLevel(l vlatte.LogLevel) *ConfigBuilder
- func (cb *ConfigBuilder) LogOutput(w io.Writer) *ConfigBuilder
- func (cb *ConfigBuilder) LogPretty(v bool) *ConfigBuilder
- func (cb *ConfigBuilder) LogVerbosity(l vlatte.LogVerbosity) *ConfigBuilder
- func (cb *ConfigBuilder) Logger(l *zerolog.Logger) *ConfigBuilder
- func (cb *ConfigBuilder) Matchers(r *matchbuild.Registry) *ConfigBuilder
- func (cb *ConfigBuilder) MaxBodyParsingLimit(n int64) *ConfigBuilder
- func (cb *ConfigBuilder) MockFileHandlers(handlers ...MockFileHandler) *ConfigBuilder
- func (cb *ConfigBuilder) MockFilePatterns(patterns ...string) *ConfigBuilder
- func (cb *ConfigBuilder) MockNotFoundStatusCode(code int) *ConfigBuilder
- func (cb *ConfigBuilder) Name(name string) *ConfigBuilder
- func (cb *ConfigBuilder) NoBodyParsing() *ConfigBuilder
- func (cb *ConfigBuilder) NoDebugHeaders() *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) Parameters(params vlatte.KV) *ConfigBuilder
- func (cb *ConfigBuilder) Port(port int) *ConfigBuilder
- func (cb *ConfigBuilder) Proxy(options ...ProxyConfigurer) *ConfigBuilder
- func (cb *ConfigBuilder) Record(options ...RecordConfigurer) *ConfigBuilder
- func (cb *ConfigBuilder) RedactHeader(names ...string) *ConfigBuilder
- func (cb *ConfigBuilder) RequestBodyParsers(bp ...RequestBodyParser) *ConfigBuilder
- func (cb *ConfigBuilder) RootDir(rootDir string) *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, clientCert string) *ConfigBuilder
- func (cb *ConfigBuilder) TemplateDataProviders(sdp []TemplateDataProvider) *ConfigBuilder
- func (cb *ConfigBuilder) TemplateEngine(e vlatte.TemplateEngine) *ConfigBuilder
- func (cb *ConfigBuilder) TemplateEnv(names ...string) *ConfigBuilder
- func (cb *ConfigBuilder) Transport(rt http.RoundTripper) *ConfigBuilder
- func (cb *ConfigBuilder) Use(fn ...func(handler http.Handler) http.Handler) *ConfigBuilder
- func (cb *ConfigBuilder) UseDescriptiveLogger() *ConfigBuilder
- func (cb *ConfigBuilder) WorkDir(dir string) *ConfigBuilder
- type ConfigFlag
- type ConfigSource
- type DebugFn
- type EchoReply
- type FilePattern
- func (p *FilePattern) Body(matchers ...vlatte.Matcher) *FilePattern
- func (p *FilePattern) BodyFile(filename string) *FilePattern
- func (p *FilePattern) ContentType(m vlatte.Matcher) *FilePattern
- func (p *FilePattern) Every() *FilePattern
- func (p *FilePattern) Filename(m vlatte.Matcher) *FilePattern
- func (p *FilePattern) Header(name string, m vlatte.Matcher) *FilePattern
- type FromTypes
- type FuncReply
- type JournalConfig
- type Kit
- type Loader
- type Mapper
- type MatcherSpec
- type Mock
- func (m *Mock) Called() bool
- func (m *Mock) Close() error
- func (m *Mock) Describe() descriptor.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) MarshalJSON() ([]byte, error)
- func (m *Mock) Name() string
- func (m *Mock) Origin() string
- func (m *Mock) Priority() int
- func (m *Mock) Steps() []vlatte.Step
- func (m *Mock) String() string
- func (m *Mock) Switch(state bool)
- func (m *Mock) UpstreamSteps() []vlatte.Step
- func (m *Mock) WireSteps() []vlatte.Step
- type MockFileHandler
- type Multipart
- func (mp *Multipart) Boundary(boundary string) *Multipart
- func (mp *Multipart) Check(engine vlatte.TemplateEngine) error
- func (mp *Multipart) Describe() descriptor.Descriptor
- func (mp *Multipart) Encode(engine vlatte.TemplateEngine, data any) (contentType string, body []byte, err error)
- func (mp *Multipart) Param(name, value string) *Multipart
- func (mp *Multipart) Template() *Multipart
- type OnComplete
- 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) Request() *RequestValues
- func (i *OnComplete) Response() *Response
- func (i *OnComplete) Transport() http.RoundTripper
- type Option
- type Part
- func (p *Part) Body(b []byte) *Part
- func (p *Part) BodyFile(filename string) *Part
- func (p *Part) BodyJSON(v any) *Part
- func (p *Part) BodyText(text string) *Part
- func (p *Part) ContentType(contentType string) *Part
- func (p *Part) Delay(d time.Duration) *Part
- func (p *Part) Filename(filename string) *Part
- func (p *Part) Header(key, value string) *Part
- func (p *Part) Name(name string) *Part
- type Problem
- type ProxyConfig
- type ProxyConfigurer
- type ProxyReply
- func (r *ProxyReply) Describe() descriptor.Descriptor
- func (r *ProxyReply) Header(key, value string) *ProxyReply
- func (r *ProxyReply) Headers(header http.Header) *ProxyReply
- func (r *ProxyReply) NewReplier(app *Server) (Replier, error)
- func (r *ProxyReply) PreserveHost() *ProxyReply
- func (r *ProxyReply) RemoveRequestHeaders(header ...string) *ProxyReply
- func (r *ProxyReply) RequestHeader(key, value string) *ProxyReply
- func (r *ProxyReply) RequestHeaders(header http.Header) *ProxyReply
- func (r *ProxyReply) SSLVerify(v bool) *ProxyReply
- func (r *ProxyReply) SkipSSLVerify() *ProxyReply
- func (r *ProxyReply) Timeout(timeout time.Duration) *ProxyReply
- func (r *ProxyReply) Transport(rt http.RoundTripper) *ProxyReply
- func (r *ProxyReply) TrimPrefix(prefix string) *ProxyReply
- func (r *ProxyReply) TrimSuffix(suffix string) *ProxyReply
- func (r *ProxyReply) XForwarded() *ProxyReply
- type RandomReply
- type Recipe
- type RecordConfig
- type RecordConfigurer
- func RecordBodyFiles(v bool) RecordConfigurer
- func RecordDir(dir string) RecordConfigurer
- func RecordExcludeResponseHeaders(names ...string) RecordConfigurer
- func RecordFilter(filter *Builder) RecordConfigurer
- func RecordFormat(format string) RecordConfigurer
- func RecordIncludeMocked(v bool) RecordConfigurer
- func RecordMaxBodySize(n int64) RecordConfigurer
- func RecordMaxInlineBody(n int64) RecordConfigurer
- func RecordMethods(methods ...string) RecordConfigurer
- func RecordPaths(globs ...string) RecordConfigurer
- func RecordRepeats(repeats vlatte.RecordRepeats) RecordConfigurer
- func RecordRequestHeaders(names ...string) RecordConfigurer
- func RecordSkipSSLVerify(v bool) RecordConfigurer
- func RecordTarget(target string) RecordConfigurer
- func RecordTransform(transform func(*RecordedMock) error) RecordConfigurer
- func RecordTransport(rt http.RoundTripper) RecordConfigurer
- type RecordedFile
- type RecordedMock
- type RecordedRequest
- type RecordedResponse
- type Replier
- type ReplierFactory
- type Reply
- func Accepted() *Reply
- func BadGateway() *Reply
- func BadRequest() *Reply
- func Created() *Reply
- func Forbidden() *Reply
- func GatewayTimeout() *Reply
- func InternalServerError() *Reply
- func MethodNotAllowed() *Reply
- func MovedPermanently(location string) *Reply
- func MultipleChoices() *Reply
- func NewReply() *Reply
- func NoContent() *Reply
- func NotFound() *Reply
- func NotImplemented() *Reply
- func NotModified() *Reply
- func OK() *Reply
- func PartialContent() *Reply
- func ServiceUnavailable() *Reply
- func Status(status int) *Reply
- func Unauthorized() *Reply
- func UnprocessableEntity() *Reply
- func (rep *Reply) Body(value []byte) *Reply
- func (rep *Reply) BodyFile(filename string) *Reply
- func (rep *Reply) BodyFileWithTemplate(filename string) *Reply
- func (rep *Reply) BodyJSON(data any) *Reply
- func (rep *Reply) BodyReader(reader io.Reader) *Reply
- func (rep *Reply) BodyTemplate(content string) *Reply
- func (rep *Reply) BodyText(text string) *Reply
- func (rep *Reply) ContentType(mime string) *Reply
- func (rep *Reply) Cookie(cookie *http.Cookie) *Reply
- func (rep *Reply) Describe() descriptor.Descriptor
- func (rep *Reply) ExpireCookie(cookie *http.Cookie) *Reply
- func (rep *Reply) Gzip() *Reply
- func (rep *Reply) Header(key, value string) *Reply
- func (rep *Reply) HeaderArr(key string, values ...string) *Reply
- func (rep *Reply) HeaderArrTemplate(key string, values ...string) *Reply
- func (rep *Reply) HeaderTemplate(key, value string) *Reply
- func (rep *Reply) JSON(payload any) *Reply
- func (rep *Reply) Multipart(mp *Multipart) *Reply
- func (rep *Reply) NewReplier(app *Server) (Replier, error)
- func (rep *Reply) PlainText(text string) *Reply
- func (rep *Reply) Problem(p *Problem) *Reply
- func (rep *Reply) SetTemplateData(data any) *Reply
- func (rep *Reply) Status(status int) *Reply
- func (rep *Reply) Trailer(key, value string) *Reply
- func (rep *Reply) TrailerArr(key string, values ...string) *Reply
- type ReplyInput
- type RequestBodyParser
- type RequestValues
- type Response
- type Scope
- type SequentialReply
- type Server
- func (app *Server) AdminURL() string
- func (app *Server) Backend() Backend
- func (app *Server) Close()
- func (app *Server) Config() *Config
- func (app *Server) Data() map[string]any
- func (app *Server) DescribeConfig() string
- func (app *Server) IsRecording() bool
- func (app *Server) Logger() *zerolog.Logger
- func (app *Server) MustReload()
- func (app *Server) MustStart()
- func (app *Server) MustStartTLS()
- func (app *Server) Name() string
- func (app *Server) Parameters() vlatte.KV
- func (app *Server) Prep(ctx context.Context, recipes ...Recipe) error
- func (app *Server) ProxyCA() *x509.Certificate
- func (app *Server) RecordingStatus() vlatte.RecordStatus
- func (app *Server) Reload() error
- func (app *Server) RequestPattern(b vlatte.Builder[*Mock, *Server]) (journal.Filter, 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)
- func (app *Server) URL(paths ...string) string
- type TemplateDataProvider
- type TemplateDataProviderInput
Examples ¶
Constants ¶
const ( // DefaultWorkDir is the work directory of a server without a name, and holds a named server's: see Config.WorkDir. DefaultWorkDir = "testdata/vlatte" // WorkDirVar, at the start of a path, stands for the server's work directory, as in "{workdir}/_mocks". WorkDirVar = "{workdir}" )
const ( // DefaultConfigFileName is the base name of the config file looked up by default: // .vlatterc.json, .vlatterc.yaml or .vlatterc.yml. DefaultConfigFileName = ".vlatterc" // EnvPrefix starts the names of the environment variables that configure a server, such as VLATTE_ADDR. EnvPrefix = "VLATTE" )
const ( HeaderAccept = "Accept" HeaderAcceptEncoding = "Accept-Encoding" HeaderContentType = "Content-Type" HeaderContentEncoding = "Content-Encoding" HeaderAllow = "Allow" HeaderAuthorization = "Authorization" HeaderContentDisposition = "Content-Disposition" HeaderVary = "Vary" HeaderOrigin = "Origin" HeaderContentLength = "Content-Length" HeaderConnection = "Connection" HeaderTrailer = "Trailer" HeaderLocation = "Location" HeaderCacheControl = "Cache-Control" HeaderCookie = "Cookie" HeaderSetCookie = "Set-Cookie" HeaderIfModifiedSince = "If-Modified-Since" HeaderLastModified = "Last-Modified" HeaderRetryAfter = "Retry-After" HeaderUpgrade = "Upgrade" HeaderWWWAuthenticate = "WWW-Authenticate" HeaderXForwardedFor = "X-Forwarded-For" HeaderXForwardedProto = "X-Forwarded-Proto" HeaderXForwardedProtocol = "X-Forwarded-Protocol" HeaderXForwardedSsl = "X-Forwarded-Ssl" HeaderXUrlScheme = "X-Url-Scheme" HeaderXHTTPMethodOverride = "X-HTTP-Method-Override" HeaderXRealIP = "X-Real-Ip" HeaderXRequestID = "X-Request-Id" HeaderXCorrelationID = "X-Correlation-Id" HeaderXRequestedWith = "X-Requested-With" HeaderServer = "Server" HeaderAccessControlRequestMethod = "Access-Control-Request-Method" HeaderAccessControlAllowOrigin = "Access-Control-Allow-Origin" HeaderAccessControlAllowMethods = "Access-Control-Allow-Methods" HeaderAccessControlAllowHeaders = "Access-Control-Allow-Headers" HeaderAccessControlExposeHeaders = "Access-Control-Expose-Headers" HeaderAccessControlMaxAge = "Access-Control-Max-Age" HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials" HeaderAccessControlRequestHeaders = "Access-Control-Request-Headers" HeaderStrictTransportSecurity = "Strict-Transport-Security" HeaderXContentTypeOptions = "X-Content-Type-Options" HeaderXXSSProtection = "X-XSS-Protection" HeaderXFrameOptions = "X-Frame-Options" HeaderContentSecurityPolicy = "Content-Security-Policy" HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only" HeaderXCSRFToken = "X-CSRF-Token" HeaderReferrerPolicy = "Referrer-Policy" // HeaderVlatteError says why vlatte, and not a mock, answered a request: one of the vlatte.Failure* values. HeaderVlatteError = vlatte.HeaderFailure )
Header names, for building and matching mocks.
const ( MIMEApplicationJSON = "application/json" MIMEApplicationCharsetUTF8 = MIMEApplicationJSON + "; " + _charsetUTF8 MIMEApplicationProblemJSON = "application/problem+json" MIMETextPlain = "text/plain" MIMETextPlainCharsetUTF8 = MIMETextPlain + "; " + _charsetUTF8 MIMETextHTML = "text/html" MIMETextHTMLCharsetUTF8 = MIMETextHTML + "; " + _charsetUTF8 MIMETextXML = "text/xml" MIMETextXMLCharsetUTF8 = MIMETextXML + "; " + _charsetUTF8 MIMEFormURLEncoded = "application/x-www-form-urlencoded" MIMEFormURLEncodedCharsetUTF8 = MIMEFormURLEncoded + "; " + _charsetUTF8 MIMEApplicationJavaScript = "application/javascript" MIMEApplicationJavaScriptCharsetUTF8 = MIMEApplicationJavaScript + "; " + _charsetUTF8 MIMEApplicationXML = "application/xml" MIMEApplicationXMLCharsetUTF8 = MIMEApplicationXML + "; " + _charsetUTF8 MIMEApplicationProtobuf = "application/protobuf" MIMEMultipartForm = "multipart/form-data" MIMEOctetStream = "application/octet-stream" )
MIME types, for building and matching mocks.
const Kind vlatte.Kind = "http"
Kind identifies HTTP mocks in protocol-neutral code, such as event listeners and callbacks.
const StatusNoMatch = http.StatusTeapot
StatusNoMatch describes an HTTP response where no Mock was found.
It uses http.StatusTeapot to reduce the chance of using the same expected response from the actual server being mocked. Basically, every request that doesn't match against a Mock, will have a response with http.StatusTeapot. It is also the default status of a failure, such as a reply that fails: see Config.ErrorStatusCode.
Variables ¶
var ( // ErrNoExpectations is returned by [Builder.Build] for a mock with no request matcher and no [Builder.Times]. ErrNoExpectations = errors.New("mock: at least 1 request matcher must be set") // ErrNoReplies is returned by [Builder.Build] for a mock with no reply: see [Builder.Reply]. ErrNoReplies = errors.New("mock: no reply set. Use .Reply() or any equivalent to set the expected mock response") )
var ( // ConfigMockFilePattern is the default filename glob pattern to search for local mock files, in the server's work // directory: the recordings of the default record directory too. ConfigMockFilePattern = append([]string{WorkDirVar + "/_mocks/*mock.yaml", WorkDirVar + "/_mocks/*mock.yml"}, recordedMockFiles(_defaultRecordDir)...) )
Defaults
var DefaultCORSConfig = CORSConfig{ AllowedOrigin: "*", AllowedMethods: strings.Join([]string{ http.MethodGet, http.MethodPost, http.MethodHead, http.MethodPut, http.MethodDelete, http.MethodPatch, }, ","), AllowedHeaders: "", AllowCredentials: false, ExposeHeaders: "", MaxAge: 0, SuccessStatusCode: http.StatusNoContent, }
DefaultCORSConfig is the CORS configuration that ConfigBuilder.CORS and the cors configuration keys start from: any origin, the methods GET, POST, HEAD, PUT, DELETE and PATCH, any header a preflight request asks for, and 204 for preflight requests.
var DefaultConfigDirectories = []string{".", "testdata"}
DefaultConfigDirectories are the directories searched for the config file, in order.
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. format is json, yaml or yml. Like a mock file, the document is data; see FromFile. A relative body_file opens from the working directory.
func FromFile ¶
FromFile builds a mock from a JSON or YAML file, chosen by its extension: .json, .yaml or .yml.
The file is data: only the settings that are templates, such as a templated reply body, are compiled, with the template engine of the server. Templates read the server's parameters, data and URL when a request arrives. 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.
func MockFileFormats ¶
func MockFileFormats() []string
MockFileFormats lists the formats of mock files and recordings, as file extensions without the dot.
Types ¶
type AdminAPI ¶
AdminAPI is an admin API the server opts into: a RESTful HTTP server of its own, apart from the mocks, that lists, adds and changes them while the server runs. Make one with github.com/caffeine-projects/vlatte/admin.New. A nil AdminAPI serves none.
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, and WorkDirVar at its work directory, as in "{workdir}/_admin". 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 Backend ¶
type Backend interface {
Listen() error
ListenTLS() error
Serve() error
Close() error
Info() *BackendInfo
}
Backend is the HTTP server that serves a mock server's handler. A mock server starts it in two steps: Listen or ListenTLS binds its address, so Info has its URL, while the server loads its mocks and starts its recording; then Serve answers the connections, those that came meanwhile included. It starts once.
type BackendConfig ¶
BackendConfig bundles the inputs a BackendFactory needs to build the Backend of a Server.
type BackendFactory ¶
type BackendFactory interface {
NewBackend(config BackendConfig) (Backend, error)
}
BackendFactory builds the Backend of a mock server. The default factory builds it on an httptest.Server.
type Builder ¶
type Builder struct {
// contains filtered or unexported fields
}
Builder describes a mock. 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, and changing it after Mock changes only the mocks built afterwards.
Mocks built from one builder share what it holds: its matchers, mappers, callbacks, steps and delay. Each has its own ID (unless set with ID), hits, count of Times and Once, enabled state, scenario binding and Replier.
func ProxyAll ¶
func ProxyAll(reply *ProxyReply) *Builder
ProxyAll returns a mock that answers the requests no other mock matches with reply: it matches any method and path, and comes last, at the priority math.MaxInt. It leaves CONNECTs alone, and, on a server that is a forward proxy, the requests in absolute form, which the proxy sends on to the hosts they name. Its description holds the reply under proxy_all, which a mock file loads back as the same mock.
func (*Builder) BasicAuth ¶
BasicAuth matches the credentials of the request's Basic Authorization header, exactly.
func (*Builder) BasicAuthMatches ¶
BasicAuthMatches defines matchers for the username and the password of the request's Basic Authorization header, as http.Request.BasicAuth reads them. Without Basic credentials, both are nil.
func (*Builder) Body ¶
Body adds matchers to the HTTP request body. With more than one, the body must match them all, such as matchers of several fields of a JSON body:
m.Body(match.JSONPath("name", match.Equal("test")), match.JSONPath("address.street", match.Contain("nowhere")))
It panics when given no matcher.
func (*Builder) Build ¶
Build makes a new Mock for app from the builder, and leaves the builder as it was. Used internally by Server.
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 response waits for 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 request's journal entry, unless Close canceled it, and never changes the response. Mock files can't set callbacks, and a mock's description leaves them out.
func (*Builder) ClientIP ¶
ClientIP defines a matcher for the address of the client, as http.Request.RemoteAddr has it, without its port. Behind a proxy it is the proxy's: X-Forwarded-For is a header, which Header matches.
func (*Builder) ContentType ¶
ContentType matches the Content-Type of the request, ignoring case. A value without parameters matches the media type alone, whatever parameters the request has, such as the boundary of a multipart form: ContentType("multipart/form-data") matches "multipart/form-data; boundary=x". A value with parameters matches the whole header.
func (*Builder) Cookie ¶
Cookie defines a matcher for the value of a cookie, by its name, which keeps its case. It reads the first cookie with that name, as http.Request.Cookie does, and nil when the request has none, which no text matches.
func (*Builder) DelayFunc ¶
DelayFunc sets a function that picks the delay before each mocked response, such as vlatte.Jitter or vlatte.UniformDistribution.
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) FormField ¶
FormField defines a matcher for a field of the body's form, urlencoded or multipart, by its name. It reads the field as http.Request.PostFormValue does: its first value, and never the query.
func (*Builder) FormFieldf ¶
FormFieldf defines a matcher for a specific form field by its key.
func (*Builder) FormFields ¶
FormFields defines a matcher for every value of a field of the body's form: a []string, empty when the form has no such field. Like FormField, it never reads the query.
func (*Builder) FormFile ¶
func (b *Builder) FormFile(name string, p *FilePattern) *Builder
FormFile adds a matcher of the files of a field of a multipart form, by the field's name: some file of the field must match p, or every one when p is Every. A request without such a file, or without a multipart form, doesn't match.
func (*Builder) Headers ¶
Headers defines a matcher for every value of a header: a []string in the order the request sent them, empty when the request has no such header. Header reads only the first value. Values a request sends in one line, such as "a, b", are one value.
func (*Builder) Host ¶
Host defines a matcher for the host the request names, without its port, whatever the port: its Host header, or the host of a request in absolute form, as a forward proxy gets, such as "api.local". An IPv6 address comes without brackets. Host names ignore case: compare them with match.EqualIgnoreCase.
func (*Builder) ID ¶
ID sets the ID of the mock, such as "users-get". 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) Map ¶
Map adds a Mapper that allows modifying the response after it was built. Multiple mappers can be added. A mapper finds the body in Body: one that streams, such as a proxy's, is read whole for it first.
func (*Builder) Matches ¶
Matches adds a matcher of the whole request: m gets the *http.Request, as the predicate of RequestMatches 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 predicate, a matcher that describes itself is described, under request.custom, so the admin API's store keeps it.
func (*Builder) Method ¶
Method sets the HTTP request methods to match, ignoring case: one, or several, of which the request has one. It panics without a method.
func (*Builder) MethodMatches ¶
MethodMatches defines a matcher.Matcher for the request method. Useful to set a Mock for multiple HTTP Request methods.
func (*Builder) OnCompleteEvent ¶
func (b *Builder) OnCompleteEvent(cfg vlatte.EventConfig) *Builder
OnCompleteEvent adds an on-complete event to the mock. It runs once the mock replied, and the response waits for it, unless cfg.AfterResponse is set: see vlatte.EventConfig.AfterResponse.
func (*Builder) PathParam ¶
PathParam defines a matcher for a parameter of the path template, by its name: the segment it takes, decoded. With URLPathTemplate("/users/{id}"), PathParam("id", match.Equal("7")) matches /users/7. Build fails when the mock has no path template, or its template has no such parameter.
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) Queries ¶
Queries define a matcher.Matcher for query parameters that contains multiple values.
func (*Builder) Reply ¶
func (b *Builder) Reply(f ReplierFactory) *Builder
Reply sets what the mock replies with. Build asks f for a new Replier for each mock, so f can serve many mocks. Reply, SequentialReply, RandomReply, ProxyReply, FuncReply and EchoReply are factories, and Shared turns any Replier into one. The mock owns the Replier f makes: when it implements io.Closer, the mock closes it when it leaves the server. A Replier that Shared gives to many mocks is never closed by them.
func (*Builder) RequestMatches ¶
RequestMatches applies the given predicate to the incoming http.Request.
func (*Builder) RequestURI ¶
RequestURI matches the path and query of the request exactly, as match.RequestURI does and a mock file's relative url, such as "/items?page=2", does: the same path, and the same parameters, in any order, each with its values in order. It panics when uri isn't a URL.
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 request plays in, such as {{ .Request.Header.Get "X-Test-Id" }}: 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 request data of reply templates, with .Provided and .Extra empty, as no mock is picked yet. It renders more than once for a request: as the mock matches, as it takes its turn and to journal the move, so a key reads the request 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 request's matching. Read a keyed instance with Server.Scenarios, and move it with Server.SetScenario and matchscenario.Key.
func (*Builder) ScenarioStateIs ¶
ScenarioStateIs mark this mock to be served only if the scenario state is equal to the given required state.
func (*Builder) ScenarioStateWillBe ¶
ScenarioStateWillBe sets the state the scenario moves to when this mock is picked to answer a request, before it answers: the next request matches in that state. With Builder.ScenarioStateIs, of two requests in that state, only one gets this mock; without it, the mock matches in every state, so every request gets it. The scenario moves even when the mock then fails to answer, as when its client leaves during its delay.
func (*Builder) SchemeMatches ¶
SchemeMatches sets a matcher.Matcher for the URL scheme part.
func (*Builder) SetSource ¶
SetSource sets the source of the Mock. This could be a filename or any relevant information about the source of the Mock. This is mostly used internally.
func (*Builder) StartScenario ¶
StartScenario sets that this mock will start a new scenario with the given name.
func (*Builder) Step ¶
Step adds steps that the body of each answer of the mock passes through, in order, before it reaches the client: to delay it, send it in parts, change it or cut it. See vlatte.Step. Each answer has a flow of its own, so a stage keeps what it counts for that answer only.
Flushes pass through the steps too, and so does the end of the answer, an empty body included. A stage that aborts the flow, with vlatte.ErrAbort or vlatte.ErrReset, cuts the answer after what it sent: the mock counts the call and runs its callbacks and events, then cuts the connection. ErrReset resets an HTTP/1 connection. A failure, such as a failing reply, is vlatte's answer, and skips the steps.
func (*Builder) Times ¶
Times sets how many requests each mock built from the builder serves: 1 or more. Each mock counts its own, so a mock built again, as Remock does, starts from zero. The last call wins.
func (*Builder) URLFragment ¶
URLFragment defines a matcher to be applied to the URL fragment: the decoded text after a "#" in the request target. An escaped "%23" is part of the path. Go's http.Client doesn't send fragments: a request with URL.Opaque set to the path and fragment, such as "/users#top", does.
func (*Builder) URLFragmentf ¶
URLFragmentf sets a Matcher that compares the URL fragment with the given value, as a glob. The expected value will be formatted with the provided format specifier.
func (*Builder) URLPathTemplate ¶
URLPathTemplate matches the path with a template, such as /users/{id}/orders/{orderId}: the path has as many segments, each literal one the same once decoded, and a non-empty one for each parameter. A parameter is a whole segment, and %7B writes a literal brace. PathParam matches a parameter, and templates read them as .Request.PathParams. A mock has one path template, which other matchers of the URL or the path add to.
func (*Builder) URLPathf ¶
URLPathf matches the path with a glob, formatted with the format specifier: only "*" is special, it crosses "/", and case counts, so "/users/*" matches "/users/7/orders", and not "/Users/7".
func (*Builder) URLf ¶
URLf matches the full URL, such as "http://127.0.0.1:8080/items?page=2", with a glob, formatted with the format specifier: only "*" is special, it crosses "/", and case counts.
func (*Builder) UpstreamStep ¶
UpstreamStep adds steps that what the mock sends on passes through, in order, as its target reads it: the body of the request a proxy reply sends, such as to delay it, send it in parts or cut it. See vlatte.Step. Steps can change its length, so the target gets it chunked. A request without a body has nothing for them.
The server reads the body of a request before it matches a mock, so the client's upload has ended by then: these steps apply to what the mock sends on, not to how it reads the client. A body the server doesn't read whole, with NoBodyParsing or past MaxBodyParsingLimit, is read from the client as the target reads it, a small piece at a time, so a stage that slows it slows the upload too, once the connection's buffers are full. A mock with wire steps takes its connection over before it replies, so it reads such a body through these steps first: they pace the upload, and a proxy's target gets the body as they passed it on, at once. A stage that aborts the flow, with vlatte.ErrAbort or vlatte.ErrReset, fails the call to the target and cuts the client's answer, once the mock counted the call.
func (*Builder) WireStep ¶
WireStep adds steps that every byte of each answer of the mock passes through, in order, as the client reads it: the status line, the headers, the framing of the body and the body, after the steps of Step. They can send what isn't HTTP: nothing at all, half the headers, garbage after a valid head. See vlatte.Step.
The mock answers on its connection, which it takes over, in HTTP/1.x, with Connection: close, so the connection ends with the answer. A request over HTTP/2 can't give its connection over: it gets vlatte's error answer. A stage that aborts the flow, with vlatte.ErrAbort or vlatte.ErrReset, has the connection closed, or reset, without the rest of the answer, once the mock counted the call and ran its callbacks and events. A failure, such as a failing reply, is vlatte's answer, and skips the steps. A recording leaves the call out.
type CORSConfig ¶
type CORSConfig struct {
// AllowedOrigin lists the allowed origins, comma-separated. * allows any. Browsers refuse * for requests with
// credentials, so with AllowCredentials the origin of the request is allowed instead.
AllowedOrigin string
AllowCredentials bool
// AllowedMethods lists the allowed methods, comma-separated. * allows the method a preflight request asks for.
AllowedMethods string
// AllowedHeaders lists the allowed headers, comma-separated. Empty, or *, allows the headers a preflight request
// asks for.
AllowedHeaders string
// ExposeHeaders lists the headers browsers let scripts read, comma-separated. Browsers read * as a header name
// for requests with credentials.
ExposeHeaders string
// MaxAge is how many seconds browsers may cache the answer to a preflight request. -1 sends none.
MaxAge int
// SuccessStatusCode is the status of the answer to a preflight request, 204 when 0. Browsers fail a preflight
// answered with a status other than 2xx.
SuccessStatusCode int
}
CORSConfig represents the possible options to configure CORS.
func (*CORSConfig) Apply ¶
func (c *CORSConfig) Apply(opts *CORSConfig)
Apply allows CORSConfig to be used as a CORSConfigurer
type CORSConfigBuilder ¶
type CORSConfigBuilder struct {
// contains filtered or unexported fields
}
CORSConfigBuilder facilitates building CORS options. It sets only the options it is given: the others keep the values they have, such as the ones of DefaultCORSConfig.
func CORS ¶
func CORS() *CORSConfigBuilder
CORS initializes a CORSConfig builder for a fluent configuration.
func (*CORSConfigBuilder) AllowCredentials ¶
func (b *CORSConfigBuilder) AllowCredentials(allow bool) *CORSConfigBuilder
AllowCredentials sets "Access-Control-Allow-Credentials" misc.Header
func (*CORSConfigBuilder) AllowMethods ¶
func (b *CORSConfigBuilder) AllowMethods(methods ...string) *CORSConfigBuilder
AllowMethods sets the allowed HTTP methods. The header "Access-Control-Allow-Methods" will be used.
func (*CORSConfigBuilder) AllowOrigin ¶
func (b *CORSConfigBuilder) AllowOrigin(origin ...string) *CORSConfigBuilder
AllowOrigin sets the allowed origins.
func (*CORSConfigBuilder) AllowedHeaders ¶
func (b *CORSConfigBuilder) AllowedHeaders(headers ...string) *CORSConfigBuilder
AllowedHeaders sets the allowed headers. It will set the header "Access-Control-Allow-Headers".
func (*CORSConfigBuilder) Apply ¶
func (b *CORSConfigBuilder) Apply(opts *CORSConfig)
Apply sets the options given to the builder on opts.
func (*CORSConfigBuilder) ExposeHeaders ¶
func (b *CORSConfigBuilder) ExposeHeaders(headers ...string) *CORSConfigBuilder
ExposeHeaders sets the header "Access-Control-Expose-Headers".
func (*CORSConfigBuilder) MaxAge ¶
func (b *CORSConfigBuilder) MaxAge(maxAge int) *CORSConfigBuilder
MaxAge sets CORS max age.
func (*CORSConfigBuilder) SuccessStatusCode ¶
func (b *CORSConfigBuilder) SuccessStatusCode(code int) *CORSConfigBuilder
SuccessStatusCode sets a custom status code returned on CORS Options request. If none is specified, the default status code is http.StatusNoContent.
type CORSConfigurer ¶
type CORSConfigurer interface {
Apply(opts *CORSConfig)
}
CORSConfigurer lets users configure CORS.
type Config ¶
type Config struct {
// Common fields
Name string
RootDir string
WorkDir string
TLSConfig *tls.Config
TLSCertificates []tls.Certificate
TLSClientCAs *x509.CertPool
Parameters vlatte.KV
Logger *zerolog.Logger
LogOutput io.Writer
LogVerbosity vlatte.LogVerbosity
LogLevel vlatte.LogLevel
LogPretty bool
LogBodyMaxSize int64
Debug bool
Colors bool
Listeners *vlatte.Listener
GlobalEvents *vlatte.Events
TemplateDataProviders []TemplateDataProvider
DebugFn DebugFn
// Matchers builds the matcher lists of mock files, and of the admin API's request queries: the built-in matchers
// and custom ones. Nil builds the built-in matchers only.
Matchers *matchbuild.Registry
// TemplateEngine compiles every template of the server's mocks. Nil uses a vlatte.GoTemplateEngine.
TemplateEngine vlatte.TemplateEngine
// TemplateEnv names the environment variables templates may read with env, from the setting 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
// ConfigSources lists where settings are read from after code, lowest precedence first.
// Nil reads DefaultConfigSources(nil): the config file, then VLATTE_* environment variables.
// An empty, non-nil slice reads nothing, so only code and defaults apply.
ConfigSources []ConfigSource
// HTTP-specific fields
Addr string
Listener net.Listener // in place of listening on Addr: see ConfigBuilder.Listener
UseHTTP2 bool
RequestWasNotMatchedStatusCode int
ErrorStatusCode int
RequestBodyParsers []RequestBodyParser
MaxBodyParsingLimit int64
NoBodyParsing bool
NoDebugHeaders bool
NoNearMisses bool
Middlewares []func(http.Handler) http.Handler
CORS *CORSConfig
BackendFactory BackendFactory
HandlerDecorator func(handler http.Handler) http.Handler
MockFileSearchPatterns []string
Loaders []Loader
Proxy *ProxyConfig
Record *RecordConfig
Admin AdminAPI
AdminStore AdminStore
Journal *JournalConfig
MockFileHandlers []MockFileHandler
HeaderNamesToRedact map[string]struct{}
UseHTTPS bool
// Transport sends what the server sends: the requests of proxy replies, of the recording target, of the forward
// proxy and of webhooks. Each takes its own transport first, when it has one: ProxyReply.Transport,
// RecordConfig.Transport, ProxyConfig.Transport or webhook.WithTransport. For upstreams with different needs,
// give each its own, or pass one that picks a transport by req.URL.Host. It is the caller's: the server never
// closes it.
//
// Nil leaves each to a transport it makes, and closes with the server. Only the transports it makes for proxy
// replies, the recording target and the forward proxy follow its TLS client certificates and CAs: the one of
// webhooks has the settings of http.DefaultTransport. A setting that only shapes those, and that a transport of the
// caller's would ignore, fails instead: a proxy reply's SSLVerify or SkipSSLVerify fails its mock,
// RecordConfig.SkipSSLVerify fails the recording, and the forward proxy's Via or SSLVerify fails New. The forward
// proxy's CONNECT tunnels don't go through a transport: with one of the caller's, they dial their host, and else
// they go through the proxy the transport the server makes picks, Via or the proxy of the environment.
Transport http.RoundTripper
// OutboundAllow and OutboundDeny limit the addresses the server connects to, for its proxy replies, the recording
// target, the forward proxy and its tunnels, 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, and through a proxy on the way, Via or the proxy of the environment, they check the
// proxy's. An IPv4 range doesn't hold IPv6 addresses: deny ::1/128 with 127.0.0.0/8. A refused connection fails
// with [vlatte.ErrOutboundRefused]. Empty, the default, refuses nothing. A transport of the caller's, such as
// [Config.Transport], dials on its own, and they don't apply.
OutboundAllow []netip.Prefix
OutboundDeny []netip.Prefix
// contains filtered or unexported fields
}
Config holds the configuration of an HTTP mock Server.
func (*Config) Apply ¶
Apply implements Option: it sets every field of conf to c's, its zero values included. Setup sets only what its methods set, so its options compose.
func (*Config) Path ¶
Path returns where the file or pattern p of the server is: a leading WorkDirVar is the server's work directory, and a relative path starts at Config.RootDir. Path(WorkDirVar) is the work directory itself.
type ConfigBuilder ¶
type ConfigBuilder struct {
// contains filtered or unexported fields
}
ConfigBuilder builds the configuration of a Server with a fluent API. 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 Setup ¶
func Setup() *ConfigBuilder
Setup initialize a new ConfigBuilder. Entrypoint to start a new custom configuration for HTTP mock servers.
func (*ConfigBuilder) Addr ¶
func (cb *ConfigBuilder) Addr(addr string) *ConfigBuilder
Addr sets a custom address for the mock HTTP server.
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) BackendFactory ¶
func (cb *ConfigBuilder) BackendFactory(factory BackendFactory) *ConfigBuilder
BackendFactory configures a custom BackendFactory used to build the underlying HTTP mock Backend for a Server.
func (*ConfigBuilder) CORS ¶
func (cb *ConfigBuilder) CORS(options ...CORSConfigurer) *ConfigBuilder
CORS configures CORS for the mock server. An answer that sends a CORS header, such as a proxied one, answers CORS by itself: the server's CORS headers aren't sent with it. A Handler reply writes its answer on top of the server's CORS headers: it should Set its CORS headers, or Del the server's.
func (*ConfigBuilder) Colors ¶
func (cb *ConfigBuilder) Colors(v bool) *ConfigBuilder
Colors enable/disable use of ANSI colors in logs.
func (*ConfigBuilder) ConfigSources ¶
func (cb *ConfigBuilder) ConfigSources(sources ...ConfigSource) *ConfigBuilder
ConfigSources sets where settings are read from after code, lowest precedence first, replacing DefaultConfigSources. With no arguments, only code and defaults apply. A Config applied later resets it, since it sets every field.
func (*ConfigBuilder) DebugFn ¶
func (cb *ConfigBuilder) DebugFn(dfn DebugFn) *ConfigBuilder
DebugFn sets the debug function.
func (*ConfigBuilder) ErrorStatusCode ¶
func (cb *ConfigBuilder) ErrorStatusCode(code int) *ConfigBuilder
ErrorStatusCode defines the status code of a response vlatte makes when serving a request fails, such as a reply that fails. It defaults to StatusNoMatch, as no-match does: the VLatte-Error header tells them apart.
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. The listeners registered with OnCompleteListener, before or after, are registered in it too, so none is dropped. Nil gives each server a registry of its own again.
func (*ConfigBuilder) GlobalEvents ¶
func (cb *ConfigBuilder) GlobalEvents(events *vlatte.Events) *ConfigBuilder
GlobalEvents sets the events that run for every mock.
func (*ConfigBuilder) HandlerDecorator ¶
func (cb *ConfigBuilder) HandlerDecorator(fn func(handler http.Handler) http.Handler) *ConfigBuilder
HandlerDecorator configures a custom HTTP handler using the default mock handler. The journal, the logs and the events tell the status it sends, when it answers in place of a mock, such as on a timeout.
func (*ConfigBuilder) Journal ¶
func (cb *ConfigBuilder) Journal(dir string) *ConfigBuilder
Journal keeps a journal of the requests 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 requests of earlier runs.
func (*ConfigBuilder) Listener ¶
func (cb *ConfigBuilder) Listener(l net.Listener) *ConfigBuilder
Listener sets an already bound listener for the mock HTTP 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) Loader ¶
func (cb *ConfigBuilder) Loader(loader Loader) *ConfigBuilder
Loader configures an additional Loader.
func (*ConfigBuilder) LogBodyMaxSize ¶
func (cb *ConfigBuilder) LogBodyMaxSize(size int64) *ConfigBuilder
LogBodyMaxSize sets the max size of the response body to be logged.
func (*ConfigBuilder) LogLevel ¶
func (cb *ConfigBuilder) LogLevel(l vlatte.LogLevel) *ConfigBuilder
LogLevel sets the level of the zerolog.Logger.
func (*ConfigBuilder) LogOutput ¶
func (cb *ConfigBuilder) LogOutput(w io.Writer) *ConfigBuilder
LogOutput sets where the server writes its logs, its debug output and the requests echo replies log, 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) LogPretty ¶
func (cb *ConfigBuilder) LogPretty(v bool) *ConfigBuilder
LogPretty enable/disable pretty logging.
func (*ConfigBuilder) LogVerbosity ¶
func (cb *ConfigBuilder) LogVerbosity(l vlatte.LogVerbosity) *ConfigBuilder
LogVerbosity sets the verbosity of informative logs.
func (*ConfigBuilder) Logger ¶
func (cb *ConfigBuilder) Logger(l *zerolog.Logger) *ConfigBuilder
Logger sets a custom zerolog.Logger.
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) MaxBodyParsingLimit ¶
func (cb *ConfigBuilder) MaxBodyParsingLimit(n int64) *ConfigBuilder
MaxBodyParsingLimit sets the limit of bytes that request body parsers should read. Zero means no limit.
func (*ConfigBuilder) MockFileHandlers ¶
func (cb *ConfigBuilder) MockFileHandlers(handlers ...MockFileHandler) *ConfigBuilder
MockFileHandlers sets MockFileHandler implementations.
func (*ConfigBuilder) MockFilePatterns ¶
func (cb *ConfigBuilder) MockFilePatterns(patterns ...string) *ConfigBuilder
MockFilePatterns sets custom Glob patterns to load mock from the file system, which may start with WorkDirVar. Defaults to ConfigMockFilePattern.
func (*ConfigBuilder) MockNotFoundStatusCode ¶
func (cb *ConfigBuilder) MockNotFoundStatusCode(code int) *ConfigBuilder
MockNotFoundStatusCode defines the status code to be used when no mock matches with an HTTP request.
func (*ConfigBuilder) Name ¶
func (cb *ConfigBuilder) Name(name string) *ConfigBuilder
Name sets a name to the mock server, which its logs show. It names the folder of its files too, in DefaultWorkDir, unless WorkDir sets another: a path inside it, which doesn't start with _, as vlatte's own folders do.
func (*ConfigBuilder) NoBodyParsing ¶
func (cb *ConfigBuilder) NoBodyParsing() *ConfigBuilder
NoBodyParsing disables request body parsing.
func (*ConfigBuilder) NoDebugHeaders ¶
func (cb *ConfigBuilder) NoDebugHeaders() *ConfigBuilder
NoDebugHeaders turns off the debug headers, such as VLatte-Matched-Mock-Id, that the server adds to its answers. VLatte-Error stays: it tells the server's own answers from a mock's.
func (*ConfigBuilder) NoNearMisses ¶
func (cb *ConfigBuilder) NoNearMisses() *ConfigBuilder
NoNearMisses turns off the report of the mocks closest to a request no mock matched, which the answer to it lists. The report runs no matcher twice: it runs those matching never reached, such as the action of a match.Peek after the part a mock differs in.
func (*ConfigBuilder) OnCompleteListener ¶
func (cb *ConfigBuilder) OnCompleteListener(name string, listener vlatte.EventListener[vlatte.OnComplete]) *ConfigBuilder
OnCompleteListener registers an on-complete event listener by name, for the servers built from the builder from then on: a server built before doesn't get it. Without EventListeners, it goes in the server's registry, or in the one an earlier option set. A name registered twice fails the server's 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) Parameters ¶
func (cb *ConfigBuilder) Parameters(params vlatte.KV) *ConfigBuilder
Parameters sets a custom reply parameters store.
func (*ConfigBuilder) Port ¶
func (cb *ConfigBuilder) Port(port int) *ConfigBuilder
Port sets a custom port to the mock HTTP server. If none is provided, a random port number will be used.
func (*ConfigBuilder) Proxy ¶
func (cb *ConfigBuilder) Proxy(options ...ProxyConfigurer) *ConfigBuilder
Proxy configures the mock server as a proxy server. Non-Matched requests will be routed based on the proxy configuration.
func (*ConfigBuilder) Record ¶
func (cb *ConfigBuilder) Record(options ...RecordConfigurer) *ConfigBuilder
Record configures recording.
func (*ConfigBuilder) RedactHeader ¶
func (cb *ConfigBuilder) RedactHeader(names ...string) *ConfigBuilder
RedactHeader hides the values of the given HTTP headers in logs and recordings. A recording writes <redacted> for the values of a response header, and matches a request header that RecordRequestHeaders names by its presence.
func (*ConfigBuilder) RequestBodyParsers ¶
func (cb *ConfigBuilder) RequestBodyParsers(bp ...RequestBodyParser) *ConfigBuilder
RequestBodyParsers adds a custom list of RequestBodyParsers.
func (*ConfigBuilder) RootDir ¶
func (cb *ConfigBuilder) RootDir(rootDir string) *ConfigBuilder
RootDir sets the directory that relative mock file patterns and recording paths start at. Absolute ones are used as they are.
func (*ConfigBuilder) Silent ¶
func (cb *ConfigBuilder) Silent() *ConfigBuilder
Silent turns the server's logs off: it sets the log level to vlatte.LogLevelDisabled. Echo replies set with EchoReply.Log still write requests to the log output.
func (*ConfigBuilder) TLSCertKeyPair ¶
func (cb *ConfigBuilder) TLSCertKeyPair(certFile, keyFile string) *ConfigBuilder
TLSCertKeyPair sets a custom public/private key pair. If none is provided, default values will be used when starting the server with Server.StartTLS or Server.MustStartTLS. If TLSConfig is set, this option will be ignored.
func (*ConfigBuilder) TLSCertificates ¶
func (cb *ConfigBuilder) TLSCertificates(certs []tls.Certificate) *ConfigBuilder
TLSCertificates sets the server TLS certificates.
func (*ConfigBuilder) TLSClientCAs ¶
func (cb *ConfigBuilder) TLSClientCAs(pool *x509.CertPool) *ConfigBuilder
TLSClientCAs sets the certificate authorities used to verify client certificates (mutual TLS).
func (*ConfigBuilder) TLSConfig ¶
func (cb *ConfigBuilder) TLSConfig(c *tls.Config) *ConfigBuilder
TLSConfig defines custom TLS configurations.
func (*ConfigBuilder) TLSMutual ¶
func (cb *ConfigBuilder) TLSMutual(certFile, keyFile, clientCert string) *ConfigBuilder
TLSMutual defines the set of root certificate authorities that the server will use. If TLSConfig is set, this option will be ignored.
func (*ConfigBuilder) TemplateDataProviders ¶
func (cb *ConfigBuilder) TemplateDataProviders(sdp []TemplateDataProvider) *ConfigBuilder
TemplateDataProviders sets template data providers.
func (*ConfigBuilder) TemplateEngine ¶
func (cb *ConfigBuilder) TemplateEngine(e vlatte.TemplateEngine) *ConfigBuilder
TemplateEngine sets the engine that compiles every template of the server's mocks: reply bodies, headers and body file names, multipart parts, and the parameters of events such as webhooks. Without one, the server uses a vlatte.GoTemplateEngine. To give Go templates more functions, set one made with vlatte.WithTemplateFuncs.
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) Transport ¶
func (cb *ConfigBuilder) Transport(rt http.RoundTripper) *ConfigBuilder
Transport sets the transport of what the server sends. See Config.Transport.
func (*ConfigBuilder) Use ¶
func (cb *ConfigBuilder) Use(fn ...func(handler http.Handler) http.Handler) *ConfigBuilder
Use adds middlewares that wrap the mock handler, to intercept requests. They run in the order they are added, across calls. The journal, the logs and the events tell the status a middleware sends, when it answers in place of a mock.
func (*ConfigBuilder) UseDescriptiveLogger ¶
func (cb *ConfigBuilder) UseDescriptiveLogger() *ConfigBuilder
UseDescriptiveLogger enable/disable the use of a more descriptive logger.
func (*ConfigBuilder) WorkDir ¶
func (cb *ConfigBuilder) WorkDir(dir string) *ConfigBuilder
WorkDir sets the directory of the server's own files: the mock files, recordings, admin mocks and journal of its defaults, whose paths start with WorkDirVar. Empty is DefaultWorkDir, or DefaultWorkDir/<name> for a named server. A relative dir starts at RootDir.
type ConfigFlag ¶
ConfigFlag describes the command-line flag of a server setting; see ConfigFlags.
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 place server settings are read from: see ConfigFile, ConfigEnv, ConfigArgs and ConfigBuilder.ConfigSources.
func ConfigArgs ¶
func ConfigArgs(args []string) ConfigSource
ConfigArgs reads server settings from command-line arguments, such as --log-level=debug. It never reads os.Args: pass the arguments, such as os.Args[1:].
func ConfigEnv ¶
func ConfigEnv() ConfigSource
ConfigEnv reads server settings from VLATTE_* environment variables, such as VLATTE_LOG_LEVEL for log.level. Any other VLATTE_* variable is an error, except VLATTE_DOCKER_HOST, which the vlatte command reads, and the VLATTE_GRPC_* ones, the gRPC server's: see mockgrpc.ConfigEnv.
func ConfigFile ¶
func ConfigFile(path string, dirs ...string) ConfigSource
ConfigFile reads server settings from a JSON or YAML file, chosen by its extension: .json, .yaml or .yml.
With no dirs, path is the file to read, and it must exist. 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 of the lookup.
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_* environment variables, then args.
type EchoReply ¶
type EchoReply struct {
// contains filtered or unexported fields
}
EchoReply configures a reply that writes the request back, as it came. It is a ReplierFactory.
func Echo ¶
func Echo() *EchoReply
Echo returns a reply that writes the request back, as it came. Mock files have no echo reply: describing a mock with it fails, so the admin API can't show the mock, nor save or store it.
func (*EchoReply) Describe ¶
func (e *EchoReply) Describe() descriptor.Descriptor
Describe implements descriptor.SelfDescriptive. Mock files have no echo reply: encoding the description fails.
func (*EchoReply) Log ¶
Log makes the reply also write each request to the server's log output, whatever its log level: see ConfigBuilder.LogOutput.
type FilePattern ¶
type FilePattern struct {
// contains filtered or unexported fields
}
FilePattern is what a file of a multipart form must have to match: its name, content type, headers and content. Start one with FileWith, and match it with Builder.FormFile. The files are the ones http.Request.ParseMultipartForm reads: parts with a field name and a filename.
func FileWith ¶
func FileWith() *FilePattern
FileWith starts a FilePattern. With no condition set, it matches any file.
func (*FilePattern) Body ¶
func (p *FilePattern) Body(matchers ...vlatte.Matcher) *FilePattern
Body sets matchers of the file's content, which all must match. The content is text, so an empty file reads "". It panics without a matcher.
func (*FilePattern) BodyFile ¶
func (p *FilePattern) BodyFile(filename string) *FilePattern
BodyFile matches a file whose content equals the named file's. The named file is read now: an error reading it makes Builder.Build fail.
func (*FilePattern) ContentType ¶
func (p *FilePattern) ContentType(m vlatte.Matcher) *FilePattern
ContentType sets a matcher of the media type of the file's Content-Type: in lower case and without parameters, as mime.ParseMediaType reads it, or "" when the file has none.
func (*FilePattern) Every ¶
func (p *FilePattern) Every() *FilePattern
Every makes the pattern match when the field has one file at least, and every one of them matches it.
func (*FilePattern) Filename ¶
func (p *FilePattern) Filename(m vlatte.Matcher) *FilePattern
Filename sets a matcher of the file's name, as Go reads it: multipart.FileHeader.Filename, the base of the name sent.
func (*FilePattern) Header ¶
func (p *FilePattern) Header(name string, m vlatte.Matcher) *FilePattern
Header adds a matcher of a header of the file's part: its first value, or "" when it has none.
type FromTypes ¶
FromTypes are the types of the target From takes: a URL, as text, of a string type of any name, or parsed.
type FuncReply ¶
type FuncReply struct {
// contains filtered or unexported fields
}
FuncReply is a reply that builds the response using the given function. It is a ReplierFactory: every mock built with it calls the same function, so whatever the function keeps is shared by those mocks.
func Func ¶
func Func(fn func(http.ResponseWriter, *RequestValues) (*Response, error)) *FuncReply
Func returns a reply that builds the response using the given function. The context of its RawRequest also ends when a step of the mock cuts the answer. 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 or store it.
func Handler ¶
func Handler(h http.HandlerFunc) *FuncReply
Handler returns a reply that delegates to the given http.HandlerFunc. The context of its request also ends when a step of the mock cuts the answer. Describing a mock with it fails, as with Func.
func (*FuncReply) Describe ¶
func (r *FuncReply) Describe() descriptor.Descriptor
Describe implements descriptor.SelfDescriptive. A mock file can't hold a function: encoding the description fails.
type JournalConfig ¶
type JournalConfig struct {
// Dir is where the journal keeps its files, across restarts: a server that starts again finds the requests it
// served before. Relative paths start at RootDir, and WorkDirVar at the server's work directory, as in
// "{workdir}/_journal". Empty keeps them in a temporary directory, which Close removes.
Dir string
// MaxEntries is how many requests the journal keeps, the newest. 0 keeps them all.
MaxEntries int
// MaxBodySize is how many bytes of a request's body the journal keeps. 0 keeps whole bodies.
MaxBodySize int64
}
JournalConfig configures the journal of a server: the requests its mocks get, of every outcome, which tests and the admin API verify and search, while the server runs: Close closes it. The requests the server answers before its mocks get them, such as CORS preflights, and those a middleware answers, aren't in it. A nil *JournalConfig keeps none.
type Kit ¶
type Kit struct {
// contains filtered or unexported fields
}
Kit is the vlatte.Kit of HTTP mocks: the server's template engine, logger and webhook transport, the template data of the request, and the directory of the mock file of the event it serves.
func (*Kit) Data ¶
Data implements vlatte.Kit: the template data of the request, as the templates of its reply read it.
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: the server's template engine.
func (*Kit) Transport ¶
func (k *Kit) Transport() http.RoundTripper
Transport implements vlatte.Kit: the server's Config.Transport, or else a transport the server makes and closes with it.
type Loader ¶
Loader loads mocks from outside the code, such as mock files. Load runs on the first Start and on every Reload, so it replaces the mocks its last run added, which Server.Remock does in one step. At Start, the server listens already, so URL is set, and serves once the loaders return.
type Mapper ¶
type Mapper func(requestValues *RequestValues, res *Response) error
Mapper is the function definition to be used to map a Mock response MockedResponse before serving it. The response is the mapper's to change, but for its Body bytes, which other responses of the mock can share: replace them, don't change them in place.
type MatcherSpec ¶
type MatcherSpec []any
MatcherSpec is a matcher as mock files write it, such as ["eqj", "{...}"] or ["not", "present"].
type Mock ¶
type Mock struct {
// contains filtered or unexported fields
}
Mock holds metadata and expectations to be matched against HTTP requests in order to serve mocked responses. This is the core entity of this project, and most features work based on it. A Builder makes it; afterwards only its enabled state and hits change.
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 reply holds, such as the idle connections of a proxy's HTTP client. 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() descriptor.Descriptor
Describe implements descriptor.SelfDescriptive: the mock in the mock file format. It leaves out callbacks, and steps that don't describe themselves. A reply a mock file can't hold, such as Echo, stays, so encoding the description fails.
func (*Mock) Disable ¶
func (m *Mock) Disable()
Disable disables the Mock. The Mock will not be eligible to be matched.
func (*Mock) Enable ¶
func (m *Mock) Enable()
Enable enables the Mock. The Mock will be eligible to be matched.
func (*Mock) Events ¶
Events returns the events the mock runs once it replied, its callbacks included.
func (*Mock) ID ¶
ID returns the ID of the mock: the one set with Builder.ID, or one generated when it was built.
func (*Mock) MarshalJSON ¶
MarshalJSON implements encoding/json.Marshaler: it encodes the mock's Mock.Describe description, and fails when the description holds a reply a mock file can't, such as Echo.
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.
func (*Mock) Priority ¶
Priority returns the priority of the mock: mocks with a lower one match first.
func (*Mock) Steps ¶
Steps returns the steps that the body of each answer of the mock passes through: see Builder.Step.
func (*Mock) UpstreamSteps ¶
UpstreamSteps returns the steps that what the mock sends on passes through: see Builder.UpstreamStep.
type MockFileHandler ¶
type MockFileHandler interface {
// Handle reads fields, the ext object of a mock file, and sets the mock through b.
// Keys are as written. Objects are map[string]any and lists []any; whole numbers that fit int64 are int64,
// and other numbers float64, from JSON and YAML alike.
// An error is a problem of the mock file's ext key.
Handle(fields map[string]any, b *Builder) error
}
MockFileHandler reads the ext object of mock files, so users can add settings of their own to mock files.
type Multipart ¶
type Multipart struct {
// contains filtered or unexported fields
}
Multipart is a multipart body, for a reply or a webhook: its subtype, boundary and parts, written with mime/multipart.Writer. Start one with MultipartForm, MultipartMixed or NewMultipart.
func MultipartForm ¶
MultipartForm starts a multipart/form-data body. Each of its parts needs a name.
func MultipartMixed ¶
MultipartMixed starts a multipart/mixed body.
func NewMultipart ¶
NewMultipart starts a body of multipart/<subtype>, such as related, alternative, byteranges or x-mixed-replace. The parts are copied: changing one afterwards doesn't change the body.
func (*Multipart) Boundary ¶
Boundary sets the boundary between the parts. Without one, a random boundary is drawn when the mock is built.
func (*Multipart) Check ¶
func (mp *Multipart) Check(engine vlatte.TemplateEngine) error
Check checks the body and compiles its templates with engine, as Encode does, without writing it: a webhook checks its body when its mock is built.
func (*Multipart) Describe ¶
func (mp *Multipart) Describe() descriptor.Descriptor
Describe implements descriptor.SelfDescriptive, as the parameters of a webhook write the body: under multipart, or multipart_template when its text is templates. A reply describes its body itself.
func (*Multipart) Encode ¶
func (mp *Multipart) Encode(engine vlatte.TemplateEngine, data any) (contentType string, body []byte, err error)
Encode writes the whole body, with its templates compiled with engine and rendered with data, under a boundary drawn now when none is set. It returns the body's Content-Type and bytes. engine can be nil when the body isn't templated. A body written at once can't pause, so a part with a delay is an error: delays apply to replies only.
func (*Multipart) Param ¶
Param adds a parameter to the Content-Type, such as type and start for multipart/related.
func (*Multipart) Template ¶
Template makes the text of the parts templates, compiled with the template engine of the server and rendered with the data of each reply: their names, filenames, content types, header values, text bodies and body file names. Byte and JSON bodies, and the content of body files, are written as they are.
type OnComplete ¶
type OnComplete struct {
// contains filtered or unexported fields
}
OnComplete implements vlatte.OnComplete for HTTP mocks. Listeners, and the callbacks of Builder.Callback, get it once the mock replied, and the response waits for them, but for those set to run after it. It's read-only: the listeners of a request run at the same time. The request's body was read: read it from Request, not from RawRequest.Body. Listeners use the context they get: it has the request's values, and the client leaving doesn't end it, as it ends the request's.
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) Kind ¶
func (i *OnComplete) Kind() vlatte.Kind
Kind implements vlatte.EventArgs: Kind, for HTTP mocks.
func (*OnComplete) Kit ¶
func (i *OnComplete) Kit() vlatte.Kit
Kit implements vlatte.EventArgs: a *Kit.
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 replied.
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) Request ¶
func (i *OnComplete) Request() *RequestValues
Request returns the request the mock replied to.
func (*OnComplete) Response ¶
func (i *OnComplete) Response() *Response
Response returns the response the mock replied with, or nil for a reply that wrote its answer itself, such as Echo.
func (*OnComplete) Transport ¶
func (i *OnComplete) Transport() http.RoundTripper
Transport is the server's Config.Transport, or else a transport the server makes and closes with it, so listeners such as webhooks send through it when they have none of their own, and their connections don't outlive the server.
type Option ¶
type Option = vlatte.Configurer[*Config]
Option configures a Server. Both Config and ConfigBuilder are options.
type Part ¶
type Part struct {
// contains filtered or unexported fields
}
Part is a part of a multipart body. Start one with NewPart.
func (*Part) Body ¶
Body sets the body of the part, written as it is. Like every body setter, it replaces the body an earlier one set.
func (*Part) BodyFile ¶
BodyFile sets the body of the part to the content of a file, read at each reply. Relative paths start at the working directory, or at the mock file's directory for mock files.
func (*Part) BodyJSON ¶
BodyJSON sets the body of the part as the JSON of v. A value that doesn't marshal makes building the mock fail.
func (*Part) BodyText ¶
BodyText sets the body of the part as text, a template when the body is templated.
func (*Part) ContentType ¶
ContentType sets the Content-Type of the part. Without one, a JSON body is application/json, and a part with a filename application/octet-stream.
func (*Part) Delay ¶
Delay makes a reply wait d before writing the part: the parts before it are sent and flushed first, so a client reads them while it waits, as in multipart/x-mixed-replace streams.
type Problem ¶
type Problem struct {
// contains filtered or unexported fields
}
Problem builds an RFC 9457 problem details object, the body Reply.Problem sends. Every member is optional: one that is never set is left out of the JSON, and a missing type means "about:blank" to clients.
func (*Problem) Detail ¶
Detail sets the human-readable explanation of this occurrence of the problem.
func (*Problem) Extension ¶
Extension sets an extension member, encoded as JSON next to the standard members. Setting a name again replaces its value. A name of a standard member (type, title, status, detail or instance) makes building the mock that replies with the problem fail.
func (*Problem) Instance ¶
Instance sets the URI reference that identifies this occurrence of the problem.
func (*Problem) Status ¶
Status sets the HTTP status code of the problem. Reply.Problem gives the response this status too. Zero leaves it out.
type ProxyConfig ¶
type ProxyConfig struct {
// Via sets the URL, http or https, of another proxy server to send the requests through, with the transport the
// proxy makes. Its credentials go in its URL: a client's Proxy-Authorization is for this proxy, and doesn't go on.
// Over https, set SSLVerify too, so they go to that proxy only. Without Via, the transport the proxy makes goes
// through the proxy of the environment, HTTP_PROXY, HTTPS_PROXY and NO_PROXY, which leaves out localhost.
Via string
// Timeout bounds the wait for the response headers of the host, connecting and sending the request included, with
// any transport, and the opening of a tunnel. 0 sets no bound of its own: the transport the proxy makes, and the
// tunnels, still give up connecting after 30s, and a TLS handshake after 10s. Setup().Proxy and the settings
// default it to 30s, as for proxy replies: a ProxyConfig without Timeout keeps it, and only the setting
// proxy.timeout sets 0.
Timeout time.Duration
// SSLVerify sets whether the transport the proxy makes, and the tunnels, verify the TLS certificates of the hosts,
// and of an https proxy on the way, Via or the one of the environment. They aren't verified by default.
SSLVerify bool
// Intercept serves the TLS of the CONNECT tunnels no mock matches itself, with a certificate for each host, signed
// by CA: the requests within are served as the server's own, so mocks answer them and recordings record them, and
// the proxy sends the rest on to their hosts. Clients must trust CA. A connection that doesn't start with TLS goes
// to its host through a tunnel.
Intercept bool
// CA is the CA that signs the certificates of the hosts Intercept serves. Without it, the server makes a CA of its
// own, which Server.ProxyCA returns, for clients to trust.
CA *tls.Certificate
// Transport sends the requests the proxy passes on, in place of the server's Config.Transport. It is the caller's:
// the server never closes it. With neither, the proxy makes a transport, which Via, Timeout and SSLVerify shape:
// Via and SSLVerify fail New with a transport of the caller's, which would ignore them. The tunnels of CONNECT
// requests go through the proxy the transport the proxy makes picks, Via or the proxy of the environment, and dial
// their hosts with a transport of the caller's.
Transport http.RoundTripper
}
ProxyConfig configures a proxy.
func (*ProxyConfig) Apply ¶
func (p *ProxyConfig) Apply(c *ProxyConfig) error
Apply sets the fields of p that aren't zero on c, so configs compose: Setup().Proxy(&ProxyConfig{SSLVerify: true}) keeps the default Timeout. A config turns no setting off.
type ProxyConfigurer ¶
type ProxyConfigurer interface {
Apply(config *ProxyConfig) error
}
ProxyConfigurer lets users configure the proxy.
type ProxyReply ¶
type ProxyReply struct {
// contains filtered or unexported fields
}
ProxyReply represents a response stub that will be the response "proxied" from the specified target. Use From to init a new ProxyReply. It is a ReplierFactory: each mock built with it gets a proxy of its own. It sends through the reply's Transport, or else the server's Config.Transport, or else a transport of its own, whose idle connections close when the mock leaves the server or the server closes.
func From ¶
func From[T FromTypes](target T) *ProxyReply
From creates a ProxyReply with the given target. The target's path and query come before the request's: with http://api/v1?tenant=a, a request to /users?page=2 goes to http://api/v1/users?tenant=a&page=2. It panics when target is a nil *url.URL, or text that url.Parse fails on.
func (*ProxyReply) Describe ¶
func (r *ProxyReply) Describe() descriptor.Descriptor
Describe describes the reply in the mock file format. The target is described as it was set, its credentials included, so the description loads back as the same reply: errors and logs hide them. ssl_verify is described only when it was set, so the description loads back on a server whose Config.Transport would refuse it.
func (*ProxyReply) Header ¶
func (r *ProxyReply) Header(key, value string) *ProxyReply
Header adds a value to a response header, which replaces the target's values of that name.
func (*ProxyReply) Headers ¶
func (r *ProxyReply) Headers(header http.Header) *ProxyReply
Headers adds the values of response headers, which replace the target's values of those names.
func (*ProxyReply) NewReplier ¶
func (r *ProxyReply) NewReplier(app *Server) (Replier, error)
NewReplier implements ReplierFactory. Each mock gets a proxy of its own: copies of the target and the headers, and, without the reply's Transport or the server's, a transport of its own.
func (*ProxyReply) PreserveHost ¶
func (r *ProxyReply) PreserveHost() *ProxyReply
PreserveHost sends the target the Host the client asked for, in place of the target's own, as for a target that serves several hosts, or that checks which host it is asked for.
func (*ProxyReply) RemoveRequestHeaders ¶
func (r *ProxyReply) RemoveRequestHeaders(header ...string) *ProxyReply
RemoveRequestHeaders removes the given headers from the request before it is sent to the proxy target.
func (*ProxyReply) RequestHeader ¶
func (r *ProxyReply) RequestHeader(key, value string) *ProxyReply
RequestHeader adds a value to a header sent to the proxy target, which replaces the client's values of that name. A hop-by-hop header, such as Connection or Upgrade, fails the build of the mock: it is about one connection, and a proxy doesn't make one up. A client's request to switch protocols goes on as the client asked. "Te: trailers" is the exception.
func (*ProxyReply) RequestHeaders ¶
func (r *ProxyReply) RequestHeaders(header http.Header) *ProxyReply
RequestHeaders adds the values of headers sent to the proxy target, which replace the client's values of those names. A hop-by-hop header, such as Connection or Upgrade, fails the build of the mock, as for RequestHeader.
func (*ProxyReply) SSLVerify ¶
func (r *ProxyReply) SSLVerify(v bool) *ProxyReply
SSLVerify sets whether the target's TLS certificate is verified, and the certificate of an https proxy on the way, from HTTPS_PROXY. They aren't by default, so a target with a self-signed certificate answers: set it for a target that gets credentials, such as https://user:pass@api.
func (*ProxyReply) SkipSSLVerify ¶
func (r *ProxyReply) SkipSSLVerify() *ProxyReply
SkipSSLVerify skips the verification of the target's TLS certificate, as a ProxyReply does unless SSLVerify(true).
func (*ProxyReply) Timeout ¶
func (r *ProxyReply) Timeout(timeout time.Duration) *ProxyReply
Timeout sets how long to wait for the response headers of the target, from the call: connecting and sending the request count too. The body then streams to the client as the target sends it, for as long as the client waits. 0 waits forever. Defaults to 30s.
func (*ProxyReply) Transport ¶
func (r *ProxyReply) Transport(rt http.RoundTripper) *ProxyReply
Transport sets the transport that sends the requests to the target, in place of the server's Config.Transport. It is the caller's: the proxy never closes it. It decides on its own whether it verifies the target, so SSLVerify and SkipSSLVerify fail the build of the mock with it, as with the server's Config.Transport.
func (*ProxyReply) TrimPrefix ¶
func (r *ProxyReply) TrimPrefix(prefix string) *ProxyReply
TrimPrefix removes the given prefix from the request path, before the target's path is added. It trims whole segments: "/api" turns "/api/users" into "/users", and "/api" into "", and leaves "/apiary" as it is.
func (*ProxyReply) TrimSuffix ¶
func (r *ProxyReply) TrimSuffix(suffix string) *ProxyReply
TrimSuffix removes the given suffix from the request path, before the target's path is added. It trims text, such as an extension: ".json" turns "/users.json" into "/users".
func (*ProxyReply) XForwarded ¶
func (r *ProxyReply) XForwarded() *ProxyReply
XForwarded sets the X-Forwarded-For, X-Forwarded-Host and X-Forwarded-Proto headers of the requests the target gets, as httputil.ProxyRequest.SetXForwarded does: the client's address, after those of the proxies the request came through, the host the client asked for, and its scheme. Without it, the target gets the client's, if any.
type RandomReply ¶
type RandomReply struct {
// contains filtered or unexported fields
}
RandomReply configures replies served at random, one per request. It is a ReplierFactory: each mock built with it picks from replies of its own.
func RandWith ¶
func RandWith(random *rand.Rand, reply ...ReplierFactory) *RandomReply
RandWith creates a new RandomReply that picks replies with the given *rand.Rand. Every mock built with the reply picks with it.
func RandWithSeed ¶
func RandWithSeed(seed int64, reply ...ReplierFactory) *RandomReply
RandWithSeed creates a new RandomReply that picks replies in a sequence reproducible by the given seed. 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 ...ReplierFactory) *RandomReply
Add adds a new Replier to the random list.
func (*RandomReply) Describe ¶
func (rep *RandomReply) Describe() descriptor.Descriptor
Describe implements descriptor.SelfDescriptive: the reply in the mock file format. It leaves out the replies that don't implement descriptor.SelfDescriptive, and the generator of RandWith.
func (*RandomReply) NewReplier ¶
func (rep *RandomReply) NewReplier(app *Server) (Replier, error)
NewReplier implements ReplierFactory. It makes the Replier of each reply, 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
// testdata/_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: the requests the recording takes go to it, before any mock, and its answers are
// recorded. It is an absolute http or https URL without a path, query or fragment, such as
// https://api.example.com. Without one, the recording takes what the forward proxy and proxy replies answer.
Target string
// Methods are the methods of the requests the recording takes, in any case. None takes every method.
Methods []string
// Paths are glob patterns of the paths of the requests the recording takes, such as /v1/*, where * matches a "/"
// too. None takes every path.
Paths []string
// Filter is a request pattern the requests the recording takes must match, made with Request(), such as
// Request().Header("X-Record", match.Equal("yes")). The recording uses its request matchers only.
Filter *Builder
// SkipSSLVerify skips the verification of the Target's TLS certificate, such as for a self-signed one. A recording
// sends the target its requests, credentials included, so the transport it makes verifies the target by default.
SkipSSLVerify bool
// Transport sends the requests to the Target, in place of the server's Config.Transport, such as one that trusts
// the target's private CA. It is the caller's: the recording never closes it. It decides on its own whether it
// verifies the target, so SkipSSLVerify fails the recording with it, as with the server's Config.Transport.
Transport http.RoundTripper
// RequestHeaders are the request headers a recording matches: the first value each had, or its absence. One that
// ConfigBuilder.RedactHeader names matches by its presence, so its value isn't written. A recording matches no
// other header.
RequestHeaders []string
// ExcludeResponseHeaders are the response headers a recording leaves out, in any case. Defaults to Set-Cookie, so
// mock files hold no session of the service. A list replaces the default.
ExcludeResponseHeaders []string
// BodyFiles writes every response body to a file of its own, next to the mock file, instead of inline.
BodyFiles bool
// MaxInlineBody is how many bytes of a body stay in memory while it is recorded: a larger one goes to a file as
// it streams, at the pace of the disk, which it waits for a second in all at most: a disk slower than that drops
// the recording, never the answer. A text body that stays in memory is written inline in the mock file. 0 means
// 1 MiB.
MaxInlineBody int64
// MaxBodySize bounds the response bodies recorded: a call with a larger one isn't recorded. 0 means 1 GiB, and a
// negative value means no limit.
MaxBodySize int64
// Repeats is what a recording keeps of a request that comes again: every response, 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
// forward proxy 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, what they match and what they keep. See Server.StartRecording.
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 Transforms to c's, so configs compose. A config turns no setting off: options such as RecordBodyFiles(false) do.
type RecordConfigurer ¶
type RecordConfigurer interface {
Apply(c *RecordConfig) error
}
RecordConfigurer lets users configure recording.
func RecordBodyFiles ¶
func RecordBodyFiles(v bool) RecordConfigurer
RecordBodyFiles sets whether every response body goes to a file of its own, instead of inline.
func RecordDir ¶
func RecordDir(dir string) RecordConfigurer
RecordDir sets the directory of the recordings. Relative paths start at Config.RootDir.
func RecordExcludeResponseHeaders ¶
func RecordExcludeResponseHeaders(names ...string) RecordConfigurer
RecordExcludeResponseHeaders sets the response headers recordings leave out, in any case, in place of the default Set-Cookie. With no names, recordings keep every response header.
func RecordFilter ¶
func RecordFilter(filter *Builder) RecordConfigurer
RecordFilter sets a request pattern the requests the recording takes must match, made with Request(). See RecordConfig.Filter.
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 RecordMaxBodySize ¶
func RecordMaxBodySize(n int64) RecordConfigurer
RecordMaxBodySize bounds the response bodies recorded. See RecordConfig.MaxBodySize.
func RecordMaxInlineBody ¶
func RecordMaxInlineBody(n int64) RecordConfigurer
RecordMaxInlineBody sets how many bytes of a body stay in memory while it is recorded. See RecordConfig.MaxInlineBody.
func RecordMethods ¶
func RecordMethods(methods ...string) RecordConfigurer
RecordMethods sets the methods of the requests the recording takes, in any case.
func RecordPaths ¶
func RecordPaths(globs ...string) RecordConfigurer
RecordPaths sets glob patterns of the paths of the requests the recording takes, such as /v1/*, where * matches a "/" too.
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(names ...string) RecordConfigurer
RecordRequestHeaders sets the request headers recordings match: the first value each had, or its absence.
func RecordSkipSSLVerify ¶
func RecordSkipSSLVerify(v bool) RecordConfigurer
RecordSkipSSLVerify sets whether the verification of the target's TLS certificate is skipped. See RecordConfig.SkipSSLVerify.
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.
func RecordTransport ¶
func RecordTransport(rt http.RoundTripper) RecordConfigurer
RecordTransport sets the transport that sends the requests to the target. See RecordConfig.Transport.
type RecordedFile ¶
type RecordedFile struct {
Filename string `json:"filename"`
ContentType string `json:"content_type,omitempty"`
Body MatcherSpec `json:"body,omitempty"`
BodyFile string `json:"body_file,omitempty"`
}
RecordedFile is a file of a recorded multipart form: a form_file pattern.
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 string `json:"method"`
// URL is the path and query, which must be the same: the parameters in any order, each with its values in order.
URL string `json:"url"`
// Header matches the request headers RecordConfig.RequestHeaders names, and the media type of a body.
Header map[string]MatcherSpec `json:"header,omitempty"`
// FormFile matches the files of a multipart form, by field name.
FormFile map[string][]RecordedFile `json:"form_file,omitempty"`
// Body matches the body. A recording matches no body it couldn't read, such as one that isn't text.
Body MatcherSpec `json:"body,omitempty"`
}
RecordedRequest is what a recording matches: the request section of its mock file.
type RecordedResponse ¶
type RecordedResponse struct {
Status int `json:"status"`
Header map[string][]string `json:"header,omitempty"`
Trailer map[string][]string `json:"trailer,omitempty"`
// Body is a text body, written inline. A body that isn't text, or is larger than RecordConfig.MaxInlineBody, goes
// to BodyFile, next to the mock file.
Body string `json:"body,omitempty"`
BodyFile string `json:"body_file,omitempty"`
// Encoding is gzip for a gzip body recorded decoded: it is compressed again when it is served.
Encoding string `json:"encoding,omitempty"`
}
RecordedResponse is a response a recording replies with: a response section of its mock file.
type Replier ¶
type Replier = vlatte.Replier[ReplyInput, *Response]
Replier builds the response of a mock. Each mock has its own, made by a ReplierFactory.
type ReplierFactory ¶
type ReplierFactory = vlatte.ReplierFactory[ReplyInput, *Response, *Server]
ReplierFactory makes the Replier of each mock: see vlatte.ReplierFactory. Reply, SequentialReply, RandomReply, ProxyReply, FuncReply and EchoReply are factories, and Shared turns any Replier into one.
func Shared ¶
func Shared(r Replier) ReplierFactory
Shared returns a ReplierFactory 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 ReplierFactory 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.
type Reply ¶
type Reply struct {
// contains filtered or unexported fields
}
Reply describes the response of a mock: its status, headers, trailers, cookies and body, any of them templates. It is a ReplierFactory: each mock built with it gets a Replier of its own, compiled with the template engine of its server, so a Reply can serve many mocks and servers, and changing it after Mock changes only the mocks built afterwards.
A Reply keeps the values it is given, such as body bytes, template data and a multipart body, without copying them, and the mocks built with it read them at each request: don't change them afterwards. Call the methods of the Reply instead, which reach the mocks built afterwards.
func Accepted ¶
func Accepted() *Reply
Accepted creates a new Reply with http.StatusAccepted already.
func BadGateway ¶
func BadGateway() *Reply
BadGateway creates a new Reply with http.StatusBadGateway already.
func BadRequest ¶
func BadRequest() *Reply
BadRequest creates a new Reply with http.StatusBadRequest already.
func Forbidden ¶
func Forbidden() *Reply
Forbidden creates a new Reply with http.StatusForbidden already.
func GatewayTimeout ¶
func GatewayTimeout() *Reply
GatewayTimeout creates a new Reply with http.StatusGatewayTimeout already.
func InternalServerError ¶
func InternalServerError() *Reply
InternalServerError creates a new Reply with http.StatusInternalServerError already.
func MethodNotAllowed ¶
func MethodNotAllowed() *Reply
MethodNotAllowed creates a new Reply with http.StatusMethodNotAllowed already.
func MovedPermanently ¶
MovedPermanently creates a new Reply with http.StatusMovedPermanently already.
func MultipleChoices ¶
func MultipleChoices() *Reply
MultipleChoices creates a new Reply with http.StatusMultipleChoices already.
func NewReply ¶
func NewReply() *Reply
NewReply creates a new Reply. Prefer to use factory functions for each status code.
func NoContent ¶
func NoContent() *Reply
NoContent creates a new Reply with http.StatusNoContent already.
func NotFound ¶
func NotFound() *Reply
NotFound creates a new Reply with http.StatusNotFound already.
func NotImplemented ¶
func NotImplemented() *Reply
NotImplemented creates a new Reply with http.StatusNotImplemented already.
func NotModified ¶
func NotModified() *Reply
NotModified creates a new Reply with http.StatusNotModified already.
func PartialContent ¶
func PartialContent() *Reply
PartialContent creates a new Reply with http.StatusPartialContent already.
func ServiceUnavailable ¶
func ServiceUnavailable() *Reply
ServiceUnavailable creates a new Reply with http.StatusServiceUnavailable already.
func Unauthorized ¶
func Unauthorized() *Reply
Unauthorized creates a new Reply with http.StatusUnauthorized already.
func UnprocessableEntity ¶
func UnprocessableEntity() *Reply
UnprocessableEntity creates a new Reply with http.StatusUnprocessableEntity already.
func (*Reply) Body ¶
Body defines the response body using a []byte. Like every body setter, it replaces the body an earlier one set.
func (*Reply) BodyFileWithTemplate ¶
BodyFileWithTemplate loads the body content from the given filename.
func (*Reply) BodyJSON ¶
BodyJSON defines the response body encoding the given value using json.Encoder.
func (*Reply) BodyReader ¶
BodyReader defines the response body using the given io.Reader.
func (*Reply) BodyTemplate ¶
BodyTemplate defines the response body using a template. The parameter content must be the actual template content that should be parsed and rendered. Use BodyFileWithTemplate function to load the template from a file.
func (*Reply) ContentType ¶
ContentType sets the response content-type misc.Header
func (*Reply) Describe ¶
func (rep *Reply) Describe() descriptor.Descriptor
Describe implements descriptor.SelfDescriptive: the reply in the mock file format. A body that isn't valid UTF-8 is described in base64.
func (*Reply) ExpireCookie ¶
ExpireCookie expires a cookie. It expires a copy, so the given cookie stays as it was.
func (*Reply) HeaderArrTemplate ¶
HeaderArrTemplate adds a header with multiple values that can have its value changed using templates.
func (*Reply) HeaderTemplate ¶
HeaderTemplate adds a header that can have its value changed using templates.
func (*Reply) Multipart ¶
Multipart defines the response body as a multipart body. The body sets the Content-Type, with its boundary: setting a Content-Type too, with Header or HeaderTemplate, makes building the mock fail.
func (*Reply) NewReplier ¶
NewReplier implements ReplierFactory. It compiles the templates of the reply with the template engine of app into a new Replier, and leaves the reply as it was.
func (*Reply) Problem ¶
Problem defines an RFC 9457 problem details response: it sets the Content-Type to MIMEApplicationProblemJSON and the body to p encoded as JSON. When p has a status, it sets the response status too, as the RFC asks them to match; a later call to Reply.Status overrides it. A nil p encodes as {}. An extension of p named after a standard member makes building the mock fail.
func (*Reply) SetTemplateData ¶
SetTemplateData sets the data model to be used by templates during response building.
type ReplyInput ¶
type ReplyInput struct {
RequestValues *RequestValues
Writer http.ResponseWriter
// contains filtered or unexported fields
}
ReplyInput is the input passed to Replier.Reply for HTTP.
type RequestBodyParser ¶
type RequestBodyParser interface {
// CanParse checks if the current request body should be parsed.
// The first parameter is the incoming content type.
CanParse(contentType string, r *http.Request) bool
// Parse parses the request body.
Parse(body []byte, r *http.Request) (any, error)
}
RequestBodyParser parses the request body if CanParse returns true. Multiple implementations of RequestBodyParser can be provided via configuration.
type RequestValues ¶
type RequestValues struct {
// ReqID identifies the request (e.g. for logging). Set by the request parser.
ReqID string
// StartedAtTime indicates when the request arrived.
StartedAtTime time.Time
// RawRequest is the original incoming http.Request.
RawRequest *http.Request
// URL is the full request url.URL, including scheme, host, port: those a request in absolute form, as a forward
// proxy gets, or an intercepted one names, and the server's otherwise.
URL *url.URL
// URLPathSegments stores path segments, each decoded: an escaped "/" stays in its segment.
// Eg.: /test/100 -> []string{"test", "100"}, and /files/a%2Fb -> []string{"files", "a/b"}
URLPathSegments []string
// RawBodyBytes is the HTTP request body bytes.
RawBodyBytes []byte
// ParsedBodyData is the parsed http.Request body parsed by a RequestBodyParser instance.
// It'll be nil if the HTTP request does not contain a body.
ParsedBodyData any
// App exposes application instance associated with the incoming HTTP request.
App *Server
// Mock is the matched Mock for the current HTTP request.
Mock *Mock
Data any
// contains filtered or unexported fields
}
RequestValues groups HTTP request data, including the parsed body. It is used by several components during the request matching phase.
func (*RequestValues) ID ¶
func (r *RequestValues) ID() string
ID returns the ID the server gave the request, as its logs and journal name it.
func (*RequestValues) OriginalRequest ¶
func (r *RequestValues) OriginalRequest() *http.Request
OriginalRequest returns the request as the server got it.
func (*RequestValues) ParsedBody ¶
func (r *RequestValues) ParsedBody() any
ParsedBody returns the request body as a RequestBodyParser parsed it, or nil when none did.
func (*RequestValues) RawBody ¶
func (r *RequestValues) RawBody() []byte
RawBody returns the request body the server read, at most ConfigBuilder.MaxBodyParsingLimit bytes: nil for GET and HEAD requests, and with ConfigBuilder.NoBodyParsing.
func (*RequestValues) StartedAt ¶
func (r *RequestValues) StartedAt() time.Time
StartedAt returns when the request arrived.
type Response ¶
type Response struct {
StatusCode int
Header http.Header
Trailer http.Header
Cookies []*http.Cookie
Body []byte
BodyCloser io.ReadCloser
BodyFilename string
Encoding string
// contains filtered or unexported fields
}
Response defines the HTTP response that will be served once a Mock is matched with an HTTP Request.
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 configures a sequence of replies, served one per request, in order, then the one set with OnSequenceEnded. It is a ReplierFactory: each mock built with it runs the sequence on its own, from the first reply.
func (*SequentialReply) Add ¶
func (r *SequentialReply) Add(reply ...ReplierFactory) *SequentialReply
Add adds a new replier to the sequence.
func (*SequentialReply) Describe ¶
func (r *SequentialReply) Describe() descriptor.Descriptor
Describe implements descriptor.SelfDescriptive: the reply in the mock file format. It leaves out the replies that don't implement descriptor.SelfDescriptive.
func (*SequentialReply) NewReplier ¶
func (r *SequentialReply) NewReplier(app *Server) (Replier, error)
NewReplier implements ReplierFactory. It makes the Replier of each reply of the sequence, so each mock has replies and a place in the sequence of its own.
func (*SequentialReply) OnSequenceEnded ¶
func (r *SequentialReply) OnSequenceEnded(reply ReplierFactory) *SequentialReply
OnSequenceEnded sets a replier to be used once the sequence is over.
type Server ¶
type Server struct {
*vlatte.Base[*Mock, *Server]
*journal.Verifier[*Mock, *Server]
// contains filtered or unexported fields
}
Server is the base for the mock server.
func New ¶
New creates a new HTTP mock Server with the given configurations. Parameter config accepts a Config or a ConfigBuilder implementation. If no configuration is provided, a default one will be used. If no port is set, it will start the server on localhost using a random port. It returns an error if a configuration fails to apply or the server cannot be built.
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) Close ¶
func (app *Server) Close()
Close closes the mock server. It closes the admin API first, which waits for the operations it serves. It cancels the on_complete events still running, such as a webhook waiting for its delay or its target, so the requests waiting for them end, and waits for those requests and for the events that run after the response. It stops the recording, and waits until it wrote what it took, and closes the forward proxy's open tunnels. It closes the idle connections of the transports it made, such as the one of webhooks. Last, it closes the journal, and removes a temporary one: verify the requests before Close, as t.Cleanup(m.Close) leaves a test to. A closed server doesn't start again.
func (*Server) Data ¶
Data returns the data templates read as .Data. Requests read the map, so don't change it: set new data instead.
func (*Server) DescribeConfig ¶
DescribeConfig describes key configurations of this Server.
func (*Server) IsRecording ¶
IsRecording reports whether a recording takes calls.
func (*Server) MustReload ¶
func (app *Server) MustReload()
MustReload reloads mocks from external sources, like the filesystem. Coded mocks will be kept. It panics if any error occurs.
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 starts TLS on a mock server. It fails immediately if any error occurs.
func (*Server) Parameters ¶
Parameters returns Params instance associated with this application.
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) ProxyCA ¶
func (app *Server) ProxyCA() *x509.Certificate
ProxyCA returns the certificate of the CA that signs the certificates of the hosts the forward proxy intercepts, for clients to trust, or nil when it doesn't intercept. See ProxyConfig.Intercept.
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) Reload ¶
Reload loads the mocks of external sources, such as mock files and the admin API's persistent store, again. Each loader replaces the mocks it added before; mocks added in code are kept. The mocks of the mock files and of the persistent store are swapped in one step, and stay as they were when a file has problems, or the persistent store can't be read or its mocks served. The loaders of Config.Loaders run after.
func (*Server) RequestPattern ¶
RequestPattern returns the filter of journal entries that the request part of b matches, as it matches a request: b is a *Builder, such as Request(), whose reply counts for nothing. Times, Once and scenarios match no request served before, so a pattern has none. It implements journal.RequestPatterns.
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 URL of another server: {{ .Data.target }}. The server keeps a copy of the map, and requests 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. It listens, so loaders can read URL, loads the mocks and starts the recording the config sets, then serves: the first request finds them. A server starts once: Start returns vlatte.ErrStarted once it started, and http.ErrServerClosed once it closed. Start is all or nothing: a start that fails to listen, load the mocks, start the recording or the admin API, or serve, stops what started and closes the server, so nothing listens, 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 requests 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.
Example ¶
package main
import (
"context"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"github.com/caffeine-projects/vlatte/mockhttp"
)
func main() {
// A target answers, and the server records what it proxies to it.
target := mockhttp.MustNew(mockhttp.Setup().Silent())
target.MustStart()
defer target.Close()
target.MustMock(mockhttp.Getf("/items").Reply(mockhttp.OK().JSON(map[string]any{"items": []int{1, 2}})))
dir, err := os.MkdirTemp("", "recordings")
if err != nil {
panic(err)
}
defer os.RemoveAll(dir)
m := mockhttp.MustNew(mockhttp.Setup().Silent())
m.MustStart()
defer m.Close()
m.MustMock(mockhttp.AnyMethod().Reply(mockhttp.From(target.URL())))
if err := m.StartRecording(mockhttp.RecordDir(dir), mockhttp.RecordTransform(func(r *mockhttp.RecordedMock) error {
r.Name = "the items"
return nil
})); err != nil {
panic(err)
}
res, err := http.Get(m.URL("/items?page=2"))
if err != nil {
panic(err)
}
res.Body.Close()
// The recordings are written once StopRecording returns.
recorded, err := m.StopRecording(context.Background())
if err != nil {
panic(err)
}
for _, r := range recorded.Recordings {
fmt.Println(r.Name, filepath.Base(r.File))
}
// A server that loads the recordings answers without the target.
target.Close()
replay := mockhttp.MustNew(mockhttp.Setup().Silent().MockFilePatterns(filepath.Join(dir, "*.mock.json")))
replay.MustStart()
defer replay.Close()
res, err = http.Get(replay.URL("/items?page=2"))
if err != nil {
panic(err)
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
panic(err)
}
fmt.Println(res.StatusCode, string(body))
}
Output: the items GET-items-page-2-a59dfd52f96e8038.mock.json 200 {"items":[1,2]}
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.
func (*Server) URL ¶
URL returns the base URL of the mock server. With paths, it joins them to it as path elements, with url.JoinPath: URL("/users", "1") is <base>/users/1, and "%3F" is a "?" in the path. A "?" or "#" in the last element starts the query or the fragment, which are appended as given, so they must already be escaped: URL("/users/1?active=true#top"). Go's http.Client doesn't send the fragment. With paths, it panics when url.JoinPath fails on the base URL.
type TemplateDataProvider ¶
type TemplateDataProvider = vlatte.TemplateDataProvider[*TemplateDataProviderInput]
TemplateDataProvider adds data to the templates of HTTP mocks, which read it as .Provided.<Key>.
type TemplateDataProviderInput ¶
type TemplateDataProviderInput struct {
// contains filtered or unexported fields
}
TemplateDataProviderInput is what a TemplateDataProvider receives for each request.
func (*TemplateDataProviderInput) Request ¶
func (p *TemplateDataProviderInput) Request() *RequestValues
Request returns the request being served, its matched mock in RequestValues.Mock.
Source Files
¶
- admin.go
- admin_store.go
- alias.go
- colors.go
- config.go
- config_schema.go
- cors.go
- doc.go
- events.go
- form_file.go
- forward.go
- http.go
- http_handler.go
- http_handler_events.go
- httpval.go
- journal.go
- kit.go
- loader.go
- mock.go
- mock_builder.go
- mock_builder_fs.go
- mock_schema.go
- oncomplete.go
- path_template.go
- problem.go
- proxy.go
- proxy_intercept.go
- record_capture.go
- record_codec.go
- record_config.go
- recording.go
- reply.go
- reply_echo.go
- reply_func.go
- reply_multipart.go
- reply_proxy.go
- reply_random.go
- reply_seq.go
- reply_shared.go
- request_body_parser.go
- response.go
- scenario.go
- server.go
- template.go
- transport.go
- tunnel.go
- wire.go
Directories
¶
| Path | Synopsis |
|---|---|
|
e2e
|
|
|
internal/testcert
command
Command testcert writes a self-signed certificate and its key, cert.pem and key.pem, to the working directory.
|
Command testcert writes a self-signed certificate and its key, cert.pem and key.pem, to the working directory. |
|
internal
|
|
|
mid
Package mid contains utilities to handle middlewares and also common middlewares used internally.
|
Package mid contains utilities to handle middlewares and also common middlewares used internally. |