Documentation ¶
Index ¶
- Constants
- Variables
- func HTMLContent(html string) (string, []byte)
- func Match(ctx context.Context, op Operator, value interface{}) (bool, error)
- func MustToJSON(v interface{}) (string, []byte)
- func MustToXML(v interface{}) (string, []byte)
- type ArrayStubs
- type Body
- type BodyOperator
- type Cookie
- type CreateBodyOperator
- type CreateOperator
- func Contains(v interface{}) CreateOperator
- func Empty() CreateOperator
- func EndWith(v string) CreateOperator
- func EqualTo(v interface{}) CreateOperator
- func Length(v int) CreateOperator
- func NotContains(v interface{}) CreateOperator
- func NotEmpty() CreateOperator
- func Regex(v string) CreateOperator
- func StartWith(v string) CreateOperator
- type ErrorDetail
- type FieldOperator
- type GrpcRequest
- type Handler
- type IncomingQueryOption
- type IncomingRequest
- type IncomingRequests
- type LastUpdatedRecord
- type LocalServer
- func (s *LocalServer) Close(ctx context.Context)
- func (s *LocalServer) Create(ctx context.Context, stubs ...*Stub) error
- func (s *LocalServer) GetIncomingRequests(ctx context.Context, option *IncomingQueryOption) ([]*IncomingRequest, error)
- func (s *LocalServer) GetURL(ctx context.Context) string
- func (s *LocalServer) SetNamespace(v string)
- func (s *LocalServer) UploadFile(ctx context.Context, fileID string, file []byte) (string, error)
- func (s *LocalServer) WithNamespace(namespace string) *LocalServer
- type Mode
- type Operator
- type OperatorName
- type Proto
- type Proxy
- type RemoteServer
- func (s *RemoteServer) Close(ctx context.Context)
- func (s *RemoteServer) Create(ctx context.Context, stubs ...*Stub) error
- func (s *RemoteServer) GetIncomingRequests(ctx context.Context, option *IncomingQueryOption) ([]*IncomingRequest, error)
- func (s *RemoteServer) GetURL(ctx context.Context) string
- func (s *RemoteServer) ReplayOnShadowServer(ctx context.Context, options ...ReplayOptionFunc) error
- func (s *RemoteServer) SetNamespace(v string)
- func (s *RemoteServer) UploadFile(ctx context.Context, fileID string, fileBody []byte) (string, error)
- func (s *RemoteServer) WithNamespace(namespace string) *RemoteServer
- func (s *RemoteServer) WithShadowServer(server Server) *RemoteServer
- type ReplayOption
- type ReplayOptionFunc
- type RequestMatching
- type ResetQueryOption
- type Response
- func (r *Response) Clone() *Response
- func (r *Response) LoadBodyFromFile(ctx context.Context, fileStorage fs.FileStorage) error
- func (r *Response) LoadBodyFromTemplate(ctx context.Context, data *TemplateData) error
- func (r *Response) Scan(val interface{}) error
- func (r *Response) Validate(ctx context.Context) error
- func (r Response) Value() (driver.Value, error)
- func (r *Response) WithBody(contentType string, body []byte) *Response
- func (r *Response) WithCookie(name string, value string) *Response
- func (r *Response) WithError(msg string, details ...*ErrorDetail) *Response
- func (r *Response) WithFileBody(contentType string, fileID string) *Response
- func (r *Response) WithHeader(name string, value string) *Response
- func (r *Response) WithRedirect(url string) *Response
- func (r *Response) WithStatusCode(s int) *Response
- func (r *Response) WriteTo(ctx context.Context, w http.ResponseWriter) error
- type ResponseError
- type ResponseScript
- type SchemaType
- type Server
- type StatusStore
- type Stub
- func (s *Stub) Clone() *Stub
- func (s *Stub) For(method string, urlMatchingFuncs ...CreateOperator) *Stub
- func (s *Stub) ForAny(urlMatchingFuncs ...CreateOperator) *Stub
- func (s *Stub) ForGRPC(urlMatchingFuncs ...CreateOperator) *Stub
- func (s *Stub) ForceJSON(ctx context.Context) string
- func (s *Stub) HasTemplate() bool
- func (s *Stub) IsReversed() bool
- func (s *Stub) Send(ctx context.Context, server Server) error
- func (s *Stub) ShouldDeactivateWhenMatched() *Stub
- func (s *Stub) ShouldDelay(d time.Duration) *Stub
- func (s *Stub) Validate(ctx context.Context) error
- func (s *Stub) WillReturn(resp *Response) *Stub
- func (s *Stub) WithCookie(name string, createFunc CreateOperator) *Stub
- func (s *Stub) WithDescription(desc string) *Stub
- func (s *Stub) WithEnableRecord(v bool) *Stub
- func (s *Stub) WithHeader(name string, createFunc CreateOperator) *Stub
- func (s *Stub) WithID(id int64) *Stub
- func (s *Stub) WithInactive() *Stub
- func (s *Stub) WithNamespace(namespace string) *Stub
- func (s *Stub) WithQuery(name string, createFunc CreateOperator) *Stub
- func (s *Stub) WithRequestBody(createFunc CreateBodyOperator) *Stub
- func (s *Stub) WithTag(tag string) *Stub
- func (s *Stub) WithTargetURL(url string) *Stub
- func (s *Stub) WithWeight(weight int) *Stub
- type StubMemory
- func (db *StubMemory) Create(ctx context.Context, stubs ...*Stub) error
- func (db *StubMemory) CreateIncomingRequest(ctx context.Context, r *IncomingRequest) error
- func (db *StubMemory) CreateProto(ctx context.Context, protos ...*Proto) error
- func (db *StubMemory) Delete(ctx context.Context, id int64) error
- func (db *StubMemory) GetAll(_ context.Context, namespace string) ([]*Stub, error)
- func (db *StubMemory) GetIncomingRequests(ctx context.Context, option *IncomingQueryOption) ([]*IncomingRequest, error)
- func (db *StubMemory) GetProtos(ctx context.Context) ([]*Proto, error)
- func (db *StubMemory) Reset(ctx context.Context, option *ResetQueryOption) error
- type StubSettings
- type StubStore
- type Template
- type TemplateData
Constants ¶
const ( Debug = "debug" Release = "release" )
Defines commone mode
const ( ContentTypeJSON = "application/json" ContentTypeXML = "text/xml" ContentTypeHTML = "text/html" ContentTypeText = "text/plain" ContentTypeMultipart = "multipart/form-data" ContentTypeForm = "application/x-www-form-urlencoded" )
Defines request content types
const ( HeaderContentType = "Content-Type" HeaderContentLength = "Content-Length" HeaderLocation = "Location" HeaderXRequestID = "X-Request-Id" )
Defines request header
const ( MethodGrpc = "grpc" ProtocolHTTP = "http" ProtocolGrpc = "grpc" )
const ResetAll = "reset_all"
const TagRecordedStub = "recorded_stub"
Used for recorded stub when recording is enabled
Variables ¶
var AllSupportedOperators = []OperatorName{ OpContaining, OpNotContaining, OpRegex, OpEqualTo, OpStartWith, OpEndWith, OpLength, OpEmpty, OpNotEmpty, }
var ReleaseMode = Release
ReleaseMode defines application mode This should be set on start up to avoid race condition
Functions ¶
func MustToJSON ¶
MustToJSON converts a struct to JSON. Panic if error
Types ¶
type ArrayStubs ¶
type ArrayStubs struct {
Stubs []*Stub `json:"stubs" yaml:"stubs"`
}
type Body ¶
type Body []byte
Body is a custom encoded body value to support submit body with base64 encoded or raw string
func (*Body) UnmarshalJSON ¶
Support submit body with base64 encoded or raw string
func (*Body) UnmarshalYAML ¶
It is more convenient to submit data with raw string in YAML
type BodyOperator ¶
type BodyOperator struct { // The content type of the request body which is one of the following values // - "application/json" // - "text/xml" // - "text/html" // - "text/plain" // - "multipart/form-data" // - "application/x-www-form-urlencoded" ContentType string `json:"content_type" yaml:"content_type"` Operator Operator `json:"operator" yaml:"operator"` // KeyPath is json or xml path // Refer to this document for json path syntax https://goessner.net/articles/JsonPath/ KeyPath string `json:"key_path" yaml:"key_path"` }
BodyOperator define operator for matching body
type Cookie ¶
type Cookie struct { Name string `json:"name" yaml:"name"` Value string `json:"value" yaml:"value"` ExpiredAt time.Time `json:"expired_at" yaml:"expired_at"` }
Cookie defines cookie
type CreateBodyOperator ¶
type CreateBodyOperator func() BodyOperator
CreateBodyOperator is alias function for creating a body operator
func BodyJSONPath ¶
func BodyJSONPath(jsonPath string, createOperator CreateOperator) CreateBodyOperator
BodyJSONPath matches request body by the json path Refer to this document for json path syntax https://goessner.net/articles/JsonPath/
func MultiPartForm ¶
func MultiPartForm(key string, createOperator CreateOperator) CreateBodyOperator
MultiPartForm to verify form value in multiple parts request
func URLEncodedBody ¶
func URLEncodedBody(key string, createOperator CreateOperator) CreateBodyOperator
URLEncodedBody to verify form value in url encoded request
type CreateOperator ¶
type CreateOperator func() Operator
CreateOperator is alias for creating an operator
func Contains ¶
func Contains(v interface{}) CreateOperator
Contains checks actual value should contain given value in parameter
func EndWith ¶
func EndWith(v string) CreateOperator
EndWith sets the start with matching logic This operator is applied for string only
func EqualTo ¶
func EqualTo(v interface{}) CreateOperator
EqualTo checks actual value should equal to given value in parameter Engine will convert actual value to same type with predefined parameter
func Length ¶
func Length(v int) CreateOperator
Length check length operator Supported data types: map, string and array of map, int, string, float, ...
func NotContains ¶
func NotContains(v interface{}) CreateOperator
NotContains checks actual value should not contain given value in parameter
func Regex ¶
func Regex(v string) CreateOperator
Regex checks actual value should match with given regex in parameter
func StartWith ¶
func StartWith(v string) CreateOperator
StartWith sets the start with matching logic This operator is applied for string only
type ErrorDetail ¶
type ErrorDetail struct { // Type defines message type of error detail. For example: common.v1.CommonError // This is to get message descriptor to encode/decode message // The proto of defined type must be included in proto compressed file Type string `json:"type,omitempty" yaml:"type"` // Value holds the payload of the error Value types.Map `json:"value,omitempty" yaml:"value"` }
ErrorDetail is to define details for error
type FieldOperator ¶
type FieldOperator struct { // FieldName is header name, cookie name or parameter name FieldName string `json:"field_name" yaml:"field_name"` Operator Operator `json:"operator" yaml:"operator"` }
FieldOperator defines operator with field name
type GrpcRequest ¶
type GrpcRequest struct { FullMethod string `json:"full_method" yaml:"full_method"` InputData types.Map `json:"input_data" yaml:"input_data"` }
GrpcRequest defines grpc request
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler handles mocking for http request
func NewHandler ¶
func NewHandler(stubStore StubStore, fileStorage fs.FileStorage) *Handler
NewHandler handles request
func (*Handler) Handle ¶
func (h *Handler) Handle(w http.ResponseWriter, r *http.Request)
Handle handles http request
func (*Handler) WithBodyStoreThreshold ¶
func (*Handler) WithNamespace ¶
WithNamespace sets namespace
type IncomingQueryOption ¶
type IncomingQueryOption struct { Namespace string `json:"namespace" yaml:"namespace"` Ids []int64 `json:"ids" yaml:"ids"` Limit int `json:"limit" yaml:"limit"` }
IncomingQueryOption incoming query option
type IncomingRequest ¶
type IncomingRequest struct { ID int64 `json:"id" yaml:"id"` Namespace string `json:"namespace" yaml:"namespace"` Tag string `json:"tag" yaml:"tag"` URL string `json:"url" yaml:"url"` Method string `json:"method" yaml:"method"` Header types.Map `json:"header" yaml:"header"` Body []byte `json:"body" yaml:"body"` CURL string `json:"curl" gorm:"column:curl" yaml:"curl"` StubID int64 `json:"stub_id" yaml:"stub_id"` }
IncomingRequest capture the incoming request
func Capture ¶
func Capture(r *http.Request, bodyThreshold int) *IncomingRequest
Capture capture the request from http request Ignore body if the given request is multiparts or its body exceeds the threshold
func (*IncomingRequest) Replay ¶
Replay replays the http request to a server This is to debug with a stub from a remote server using IDE
func (*IncomingRequest) ReserveRequest ¶
ReserveRequest converts the saved data to request
func (*IncomingRequest) WithNamespace ¶
func (i *IncomingRequest) WithNamespace(v string) *IncomingRequest
WithNamespace sets namespace
type IncomingRequests ¶
type IncomingRequests struct {
Requests []*IncomingRequest `json:"requests" yaml:"requests"`
}
type LastUpdatedRecord ¶
LastUpdatedRecord holds the id and updated at
type LocalServer ¶
type LocalServer struct {
// contains filtered or unexported fields
}
LocalServer is local server for unit test
func NewLocalServerWithReporter ¶
func NewLocalServerWithReporter(t *testing.T) *LocalServer
NewLocalServerWithReporter inititial a server Automatically clean up data when test is completed
func (*LocalServer) Create ¶
func (s *LocalServer) Create(ctx context.Context, stubs ...*Stub) error
Create creates stubs in local server
func (*LocalServer) GetIncomingRequests ¶
func (s *LocalServer) GetIncomingRequests(ctx context.Context, option *IncomingQueryOption) ([]*IncomingRequest, error)
GetIncomingRequests gets recorded incoming requests
func (*LocalServer) GetURL ¶
func (s *LocalServer) GetURL(ctx context.Context) string
GetURL gets root url of server
func (*LocalServer) SetNamespace ¶
func (s *LocalServer) SetNamespace(v string)
SetNamespace sets namespace which can be used for isolating test data for each testing
func (*LocalServer) UploadFile ¶
UploadFile upload file to server
func (*LocalServer) WithNamespace ¶
func (s *LocalServer) WithNamespace(namespace string) *LocalServer
WithNamespace sets namespace with chaining style
type Operator ¶
type Operator struct { // OperatorName is the name of operator which is one of the following values // - "contains" // - "not_contains" // - "regex" // - "equal_to" // - "start_with" // - "end_with" // - "length" // - "empty" // - "not_empty" Name OperatorName `json:"name" yaml:"name"` // Value the expected value, which will be compared with value from incoming request Value interface{} `json:"value" yaml:"value"` }
Operator defines operator name and expected value
type OperatorName ¶
type OperatorName string
OperatorName is alias for operator name
const ( OpContaining OperatorName = "contains" OpNotContaining OperatorName = "not_contains" OpRegex OperatorName = "regex" OpEqualTo OperatorName = "equal_to" OpStartWith OperatorName = "start_with" OpEndWith OperatorName = "end_with" OpLength OperatorName = "length" OpEmpty OperatorName = "empty" OpNotEmpty OperatorName = "not_empty" )
Defines common operator name Remember to add to AllSupportedOperators
type Proto ¶
type Proto struct { ID int64 `json:"id" yaml:"id"` Name string `json:"name" yaml:"name"` FileID string `json:"file_id" yaml:"file_id"` Methods []string `json:"methods" yaml:"methods" gorm:"serializer:json"` Types []string `json:"types" yaml:"types" gorm:"serializer:json"` CreatedAt time.Time `json:"created_at,omitempty" yaml:"created_at"` UpdatedAt time.Time `json:"updated_at,omitempty" yaml:"updated_at"` }
Proto db model for proto
type Proxy ¶
type Proxy struct { // TargetURL is the root url of the target server // The relative path will be parsed from incoming request TargetURL string `json:"target_url,omitempty" yaml:"target_url"` // TargetPath is the relative path of the target API // This is optional field, if not provided, it will be the same as original request path TargetPath string `json:"target_path,omitempty" yaml:"target_path"` // EnableRecord is to enable/disable recording response from remote server // A stub will be automatically created in stub store EnableRecord bool `json:"enable_record,omitempty" yaml:"enable_record"` }
Proxy defines proxy settings
type RemoteServer ¶
type RemoteServer struct {
// contains filtered or unexported fields
}
RemoteServer communicates with remote mock server
func NewRemoteServer ¶
func NewRemoteServer(rootURL string) *RemoteServer
NewRemoteServer returns a new instance
func NewRemoteServerWithReporter ¶
func NewRemoteServerWithReporter(t *testing.T, rootURL string) *RemoteServer
NewRemoteServerWithReporter inititial a server Automatically clean up data when test is completed
func (*RemoteServer) Close ¶
func (s *RemoteServer) Close(ctx context.Context)
Close clean up server data
func (*RemoteServer) Create ¶
func (s *RemoteServer) Create(ctx context.Context, stubs ...*Stub) error
Create creates stubs in remote server
func (*RemoteServer) GetIncomingRequests ¶
func (s *RemoteServer) GetIncomingRequests(ctx context.Context, option *IncomingQueryOption) ([]*IncomingRequest, error)
GetIncomingRequests gets recorded incoming requests
func (*RemoteServer) GetURL ¶
func (s *RemoteServer) GetURL(ctx context.Context) string
GetURL gets root url of server
func (*RemoteServer) ReplayOnShadowServer ¶
func (s *RemoteServer) ReplayOnShadowServer(ctx context.Context, options ...ReplayOptionFunc) error
ReplayOnShadowServer replays incoming requests (from remote server) to a shadow server (local server) By default, only the last request will be replayed. Use option to change replay option This is to debug the stub on a remote server using IDE
func (*RemoteServer) SetNamespace ¶
func (s *RemoteServer) SetNamespace(v string)
SetNamespace sets namespace which can be used for isolating test data for each testing
func (*RemoteServer) UploadFile ¶
func (s *RemoteServer) UploadFile(ctx context.Context, fileID string, fileBody []byte) (string, error)
UploadFile upload file to server
func (*RemoteServer) WithNamespace ¶
func (s *RemoteServer) WithNamespace(namespace string) *RemoteServer
WithNamespace sets namespace which can be used for isolating test data for each testing
func (*RemoteServer) WithShadowServer ¶
func (s *RemoteServer) WithShadowServer(server Server) *RemoteServer
WithShadowServer sets shadow server
type ReplayOption ¶
type ReplayOption struct {
// contains filtered or unexported fields
}
ReplayOption defines replaying parameter
type ReplayOptionFunc ¶
type ReplayOptionFunc func(*ReplayOption)
ReplayOptionFunc is function to modify replay option
func ReplayWithLimit ¶
func ReplayWithLimit(limit int) ReplayOptionFunc
ReplayWithLimit sets a limit
func ReplayWithRequestID ¶
func ReplayWithRequestID(ids ...int64) ReplayOptionFunc
ReplayWithRequestID replay with a set of captured request id
type RequestMatching ¶
type RequestMatching struct { // Rules to match the request method GET, POST, PUT, DELETE, PATCH Method string `json:"method,omitempty" yaml:"method"` // Rules to match the url URL []Operator `json:"url,omitempty" yaml:"url"` // Rules to match header name Header []FieldOperator `json:"header,omitempty" yaml:"header"` // Rules to match cookie Cookie []FieldOperator `json:"cookie,omitempty" yaml:"cookie"` // Rules to match request query Query []FieldOperator `json:"query,omitempty" yaml:"query"` // Rules to match request body by xml or json path Body []BodyOperator `json:"body,omitempty" yaml:"body"` }
RequestMatching defines request matching
func (*RequestMatching) Scan ¶
func (r *RequestMatching) Scan(val interface{}) error
Scan implements sqlx JSON scan method
type ResetQueryOption ¶
type Response ¶
type Response struct { // Required. Define the response status code // GRPC. Default 0 OK: https://grpc.github.io/grpc/core/md_doc_statuscodes.html // HTTP. Default 200 OK: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html StatusCode int `json:"status_code,omitempty" yaml:"status_code"` // Body defines response body // Client can submit raw JSON object or base64 encoded string for HTML, XML, ... via API // If client submits stubs using YAML format via API, then raw string can be used for any text based content Body Body `json:"body,omitempty" yaml:"body"` // This is the id of uploaded file that can be used to simulate the download // Or can be used to respond a large data payload which is not suitable to save in database BodyFile string `json:"body_file,omitempty" yaml:"body_file"` // Optional. Define response cookies // This is not applied for GRPC Cookies []Cookie `json:"cookies,omitempty" yaml:"cookies"` // Optional. Define response http headers // This is equivalent to response metadata in GRPC Header map[string]string `json:"header,omitempty" yaml:"header"` // Error is optional. Defines response error for grpc // This is not applied for HTTP since body and status code can be used Error *ResponseError `json:"error,omitempty" yaml:"error"` // Optional. If defined, then executed template will override response data Template *Template `json:"template,omitempty" yaml:"template"` }
Response defines a response
func HTMLResponse ¶
HTMLResponse is convenient constructor to initialize response with htnl body
func JSONResponse ¶
func JSONResponse(body interface{}) *Response
JSONResponse is convenient constructor to initialize response with JSON body The input parameter will be decoded to JSON
func NewResponseFromHTTP ¶
NewResponseFromHTTP parses from http response
func XMLResponse ¶
func XMLResponse(body interface{}) *Response
XMLResponse is convenient constructor to initialize response with XML body The input parameter will be decoded to XML
func (*Response) LoadBodyFromFile ¶
LoadBodyFromFile loads body from file storage
func (*Response) LoadBodyFromTemplate ¶
func (r *Response) LoadBodyFromTemplate(ctx context.Context, data *TemplateData) error
LoadBodyFromTemplate parses dynamic response from template
func (*Response) WithCookie ¶
WithCookie set cookies
func (*Response) WithError ¶
func (r *Response) WithError(msg string, details ...*ErrorDetail) *Response
func (*Response) WithFileBody ¶
WithFileBody sets file id for response body This should be used for large data response such as images, pdf, ... which are too large to store at database This can also be used to simulate the download request Handler will download file by this id and assign to body
func (*Response) WithHeader ¶
WithHeader sets header
func (*Response) WithRedirect ¶
WithRedirect sets redirect url Use WithStatusCode if want to customize the redirect code
func (*Response) WithStatusCode ¶
WithStatusCode sets the status code
type ResponseError ¶
type ResponseError struct { Message string `json:"message,omitempty" yaml:"message"` Details []*ErrorDetail `json:"details,omitempty" yaml:"details"` }
ResponseError defines the response error. Only applicable for grpc This is equivalent to status.Status in GRPC
func (*ResponseError) Clone ¶
func (r *ResponseError) Clone() *ResponseError
Clone clones the response error and its properties
type ResponseScript ¶
type ResponseScript struct { StatusCode int `json:"status_code,omitempty" yaml:"status_code"` Body string `json:"body,omitempty" yaml:"body"` Cookies []Cookie `json:"cookies,omitempty" yaml:"cookies"` Headers map[string]string `json:"headers,omitempty" yaml:"headers"` Error *ResponseError `json:"error,omitempty" yaml:"error"` }
ResponseScript represents for http response script
func (*ResponseScript) AssignTo ¶
func (s *ResponseScript) AssignTo(r *Response)
type SchemaType ¶
type SchemaType string
const ( SchemaTypeJSON SchemaType = "json" SchemaTypeYAML SchemaType = "yaml" )
type Server ¶
type Server interface { SetNamespace(v string) GetURL(ctx context.Context) string Create(ctx context.Context, stubs ...*Stub) error UploadFile(ctx context.Context, fileID string, file []byte) (string, error) Close(ctx context.Context) }
Server defines server interface
type StatusStore ¶
type StatusStore interface { GetLastUpdatedStub(ctx context.Context, namespace string) (*LastUpdatedRecord, error) GetLastUpdatedProto(ctx context.Context) (*LastUpdatedRecord, error) }
StatusStore defines interface to get latest updated information
type Stub ¶
type Stub struct { ID int64 `json:"id" yaml:"id"` // Description describes the stub Description string `json:"description,omitempty" yaml:"description"` // WithNamespace sets namespace which can be used for isolating test data for each testing // This can be applied for the unit test which uses different test server for different test // With integration or unit test with single test server (which is not recommended), namespace should be empty Namespace string `json:"namespace,omitempty" yaml:"namespace"` // Tag is to add custom tag for grouping stub // Owner can add whatever they want to classify the stub Tag string `json:"tag,omitempty" yaml:"tag"` // Protocol defines protocol of incoming requests // Value is either: http or grpc. Default value is http Protocol string `json:"protocol,omitempty" yaml:"protocol"` // Matching rules which will be matched against the incoming requests Request *RequestMatching `json:"request,omitempty" yaml:"request"` // The expected response which includes the body, header and cookies Response *Response `json:"response,omitempty" yaml:"response"` // The mock server will act as reserved proxy if this settings are provided Proxy *Proxy `json:"proxy,omitempty" yaml:"proxy"` Active bool `json:"active,omitempty" yaml:"active"` // WithWeight sets weight. The higher weight, the higher priority // It is sometimes the case that you'll want to declare two or more stub mappings that "overlap", // in that a given request would be a match for more than one of them // By default, the most recently added matching stub will be used to satisfy the request // However, in some cases it is useful to exert more control Weight int `json:"weight,omitempty" yaml:"weight"` Settings StubSettings `json:"settings,omitempty" yaml:"settings"` CreatedAt time.Time `json:"created_at,omitempty" yaml:"created_at"` UpdatedAt time.Time `json:"updated_at,omitempty" yaml:"updated_at"` }
Stub defines a stub
func SelectStubs ¶
SelectStubs gets the item with the highest priority. If weight is not set, then get the latest
func (*Stub) For ¶
func (s *Stub) For(method string, urlMatchingFuncs ...CreateOperator) *Stub
For sets http request method and matching functions for URL If method is empty, it will be ignored with matching logic
func (*Stub) ForAny ¶
func (s *Stub) ForAny(urlMatchingFuncs ...CreateOperator) *Stub
ForAny for matching request with any method
func (*Stub) ForGRPC ¶
func (s *Stub) ForGRPC(urlMatchingFuncs ...CreateOperator) *Stub
ForGRPC for matching request with grpc method
func (*Stub) HasTemplate ¶
HasTemplate returns true if response template is defined
func (*Stub) IsReversed ¶
IsReversed returns true if stub is reverse proxy
func (*Stub) ShouldDeactivateWhenMatched ¶
ShouldDeactivateWhenMatched deactivates when matched
func (*Stub) ShouldDelay ¶
ShouldDelay sets delay duration Use this to simulate the slow API response time
func (*Stub) WillReturn ¶
WillReturn sets the response
func (*Stub) WithCookie ¶
func (s *Stub) WithCookie(name string, createFunc CreateOperator) *Stub
WithCookie sets cookie matching operator
func (*Stub) WithDescription ¶
WithDescription sets description
func (*Stub) WithEnableRecord ¶
WithEnableRecord enables recording proxy as a stub
func (*Stub) WithHeader ¶
func (s *Stub) WithHeader(name string, createFunc CreateOperator) *Stub
WithHeader sets header matching operator
func (*Stub) WithNamespace ¶
WithNamespace sets namespace which can be used for isolating test data for each testing This can be applied for the unit test which uses different test server for different test With integration or unit test with single test server (which is not recommended), namespace should be empty
func (*Stub) WithQuery ¶
func (s *Stub) WithQuery(name string, createFunc CreateOperator) *Stub
WithQuery sets query matching operator
func (*Stub) WithRequestBody ¶
func (s *Stub) WithRequestBody(createFunc CreateBodyOperator) *Stub
WithRequestBody sets body matching operator
func (*Stub) WithTargetURL ¶
WithTargetURL sets base target url, request will be forwarded to the given url
func (*Stub) WithWeight ¶
WithWeight sets weight. The higher weight, the higher priority It is sometimes the case that you'll want to declare two or more stub mappings that "overlap", in that a given request would be a match for more than one of them By default, the most recently added matching stub will be used to satisfy the request However, in some cases it is useful to exert more control
type StubMemory ¶
type StubMemory struct {
// contains filtered or unexported fields
}
StubMemory implements in memory store which using for unit test
func (*StubMemory) Create ¶
func (db *StubMemory) Create(ctx context.Context, stubs ...*Stub) error
Create adds to memory
func (*StubMemory) CreateIncomingRequest ¶
func (db *StubMemory) CreateIncomingRequest(ctx context.Context, r *IncomingRequest) error
CreateIncomingRequest saves the incomes request
func (*StubMemory) CreateProto ¶
func (db *StubMemory) CreateProto(ctx context.Context, protos ...*Proto) error
func (*StubMemory) Delete ¶
func (db *StubMemory) Delete(ctx context.Context, id int64) error
Delete deletes a stub
func (*StubMemory) GetIncomingRequests ¶
func (db *StubMemory) GetIncomingRequests(ctx context.Context, option *IncomingQueryOption) ([]*IncomingRequest, error)
GetIncomingRequests returns incoming requests
func (*StubMemory) GetProtos ¶
func (db *StubMemory) GetProtos(ctx context.Context) ([]*Proto, error)
func (*StubMemory) Reset ¶
func (db *StubMemory) Reset(ctx context.Context, option *ResetQueryOption) error
Reset clear data
type StubSettings ¶
type StubSettings struct { // This is to disable the matched stub, it is not used for the next request. // In the following example, the first request will return the first stub with higher weight, // then that stub is not available for the next request anymore DeactivateWhenMatched bool `json:"deactivate_when_matched,omitempty" yaml:"deactivate_when_matched"` // It is sometimes we want to simulate slow response API. // Rio supports this feature by set delay duration DelayDuration time.Duration `json:"delay_duration,omitempty" swaggertype:"primitive,integer" yaml:"delay_duration"` // StoreVersion is a system field to control data structure version for stub // Value will be overrided by system StoreVersion int `json:"store_version,omitempty" yaml:"store_version"` }
StubSettings stub settings
func (*StubSettings) Scan ¶
func (r *StubSettings) Scan(val interface{}) error
Scan implements sqlx JSON scan method
type StubStore ¶
type StubStore interface { Create(ctx context.Context, stubs ...*Stub) error Delete(ctx context.Context, id int64) error GetAll(ctx context.Context, namespace string) ([]*Stub, error) CreateProto(ctx context.Context, protos ...*Proto) error GetProtos(ctx context.Context) ([]*Proto, error) CreateIncomingRequest(ctx context.Context, r *IncomingRequest) error GetIncomingRequests(ctx context.Context, option *IncomingQueryOption) ([]*IncomingRequest, error) Reset(ctx context.Context, option *ResetQueryOption) error }
StubStore stores the stub information
type Template ¶
type Template struct { // Supported json and yaml. Default value is yaml ScriptSchemaType SchemaType `json:"script_schema_type" yaml:"script_schema_type"` // Script is content of template file. See ResponseScript for the detail structure Script string `json:"script" yaml:"script"` }
Template defines setting for response template
func (*Template) Execute ¶
func (t *Template) Execute(ctx context.Context, data *TemplateData) (*ResponseScript, error)
Execute executes the template. Only go-template is supported at the moment For supported function in Go template, see http://masterminds.github.io/sprig/
type TemplateData ¶
type TemplateData struct { // Request is the incoming request // Which can be accessed from template as {{ .Request.<FielName> }} Request *http.Request `json:"request,omitempty" yaml:"request"` // Grpc is grpc request // Which can be accessed from template as {{ .Grpc.<FielName> }} Grpc *GrpcRequest `json:"grpc,omitempty" yaml:"grpc"` // contains filtered or unexported fields }
TemplateData holds all available data for feeding to template Either HTTP or GRPC is supported
func (*TemplateData) JSONBody ¶
func (t *TemplateData) JSONBody() map[string]interface{}
JSONBody parses request body (or request parameter in grpc) to json Panic if error for more convenient when using with template