Skip to content
This repository has been archived by the owner on Jan 29, 2024. It is now read-only.

Commit

Permalink
Add support for error responses
Browse files Browse the repository at this point in the history
  • Loading branch information
joshuaspence committed Jan 22, 2023
1 parent 80d5528 commit 5667280
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
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

0 comments on commit 5667280

Please sign in to comment.