Skip to content
This repository was archived by the owner on Jan 29, 2024. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions pkg/mockclient/expectations.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ package mockclient

import (
"fmt"
"reflect"
"time"
)

// Expectation defines the complete request/response interaction for a given scenario
type Expectation struct {
Request *RequestMatcher `json:"httpRequest"`
Response *ActionResponse `json:"httpResponse,omitempty"`
Error *ActionError `json:"httpError,omitempty"`
Times *Times `json:"times,omitempty"`
}

Expand All @@ -28,6 +30,11 @@ type ActionResponse struct {
Delay *Delay `json:"delay,omitempty"`
}

// ActionError defines the failure mode
type ActionError struct {
DropConnection bool `json:"dropConnection,omitempty"`
}

// ResponseBody defines the request body the MockServer will return when serving a matched response
type ResponseBody struct {
Type string `json:"type"`
Expand Down Expand Up @@ -60,13 +67,22 @@ func CreateExpectation(opts ...ExpectationOption) *Expectation {
Path: "/(.*)",
},
Response: &ActionResponse{},
Error: &ActionError{},
}

// Append all options that are set (discard defaults)
for _, opt := range opts {
e = opt(e)
}

if reflect.DeepEqual(e.Response, &ActionResponse{}) {
e.Response = nil
}

if reflect.DeepEqual(e.Error, &ActionError{}) {
e.Error = nil
}

return e
}

Expand Down Expand Up @@ -196,6 +212,15 @@ func ThenResponseDelay(delay time.Duration) ExpectationOption {
}
}

// ThenDropConnection creates an action that prematurely closes the connection
func ThenDropConnection() ExpectationOption {
return func(e *Expectation) *Expectation {
r := e.Error
r.DropConnection = true
return e
}
}

func boolPointer(value bool) *bool {
b := value
return &b
Expand Down
9 changes: 9 additions & 0 deletions pkg/mockclient/expectations_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,15 @@ func TestExpectations(t *testing.T) {
"unlimited" : false
}
}`},
{"Path should be matched and then an error occurs", CreateExpectation(WhenRequestPath("/path"), ThenDropConnection()), `
{
"httpRequest": {
"path": "/path"
},
"httpError": {
"dropConnection": true
}
}`},
}

for _, tc := range testCases {
Expand Down