Skip to content

Commit 0506148

Browse files
authored
Merge pull request #22 from StephanHCB/issue-21-interaction-checker
Issue 21 interaction checker
2 parents 70ccc61 + d3941b9 commit 0506148

File tree

5 files changed

+177
-15
lines changed

5 files changed

+177
-15
lines changed

.github/workflows/go.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ jobs:
2020
- name: Set up Go
2121
uses: actions/setup-go@v2
2222
with:
23-
go-version: '1.18'
23+
go-version: '1.20'
2424

2525
- name: Build
2626
run: go build -v ./...

README.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,13 @@ Useful for unit testing.
109109
mockClient := aurestmock.New(mockResponses, mockErrors)
110110
```
111111

112+
#### 1c. Or use verifier (super-basic consumer interaction testing)
113+
114+
This mock client doesn't make actual requests, but instead you set up a list of
115+
expected interactions.
116+
117+
This allows doing very simple consumer tests, useful mostly for their documentation value.
118+
112119
#### 2. Response recording
113120

114121
If your tests use Option 1a (playback), you should insert a response recorder in your production stack.

go.mod

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,5 @@ require (
1212
require (
1313
github.com/davecgh/go-spew v1.1.1 // indirect
1414
github.com/pmezard/go-difflib v1.0.0 // indirect
15-
github.com/stretchr/objx v0.5.0 // indirect
1615
gopkg.in/yaml.v3 v3.0.1 // indirect
1716
)

go.sum

Lines changed: 0 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,16 @@
11
github.com/StephanHCB/go-autumn-logging v0.3.0 h1:G0zs8xoth8i8mOeoFgG3Dvk6dIY9dPPJ7wkm6mjaPyY=
22
github.com/StephanHCB/go-autumn-logging v0.3.0/go.mod h1:dPABYdECU3XrFib03uXbQFVLftUP5c4YaKSineiw37U=
3-
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
43
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
54
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
65
github.com/go-http-utils/headers v0.0.0-20181008091004-fed159eddc2a h1:v6zMvHuY9yue4+QkG/HQ/W67wvtQmWJ4SDo9aK/GIno=
76
github.com/go-http-utils/headers v0.0.0-20181008091004-fed159eddc2a/go.mod h1:I79BieaU4fxrw4LMXby6q5OS9XnoR9UIKLOzDFjUmuw=
87
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
98
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
10-
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
11-
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
12-
github.com/stretchr/objx v0.5.0 h1:1zr/of2m5FGMsad5YfcqgdqdWrIhu+EBEJRhR1U7z/c=
13-
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
14-
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
15-
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
16-
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
17-
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
18-
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
199
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
2010
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
21-
github.com/tidwall/tinylru v1.1.0 h1:XY6IUfzVTU9rpwdhKUF6nQdChgCdGjkMfLzbWyiau6I=
22-
github.com/tidwall/tinylru v1.1.0/go.mod h1:3+bX+TJ2baOLMWTnlyNWHh4QMnFyARg2TLTQ6OFbzw8=
2311
github.com/tidwall/tinylru v1.2.1 h1:VgBr72c2IEr+V+pCdkPZUwiQ0KJknnWIYbhxAVkYfQk=
2412
github.com/tidwall/tinylru v1.2.1/go.mod h1:9bQnEduwB6inr2Y7AkBP7JPgCkyrhTV/ZpX0oOOpBI4=
2513
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
2614
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
27-
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
2815
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
2916
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

implementation/verifier/verifier.go

Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
1+
package aurestverifier
2+
3+
import (
4+
"context"
5+
"encoding/json"
6+
"errors"
7+
"fmt"
8+
aurestclientapi "github.com/StephanHCB/go-autumn-restclient/api"
9+
"io"
10+
"net/http"
11+
"net/url"
12+
"sort"
13+
"strings"
14+
)
15+
16+
type VerifierImpl struct {
17+
expectations []Expectation
18+
firstUnexpected *Request
19+
}
20+
21+
type Request struct {
22+
Name string // key for the request
23+
Method string
24+
Header http.Header // currently not tested, just supplied as documentation for now
25+
Url string
26+
Body interface{}
27+
}
28+
29+
type ResponseOrError struct {
30+
Response aurestclientapi.ParsedResponse
31+
Error error
32+
}
33+
34+
type Expectation struct {
35+
Request Request
36+
Response ResponseOrError
37+
Matched bool
38+
}
39+
40+
func (e Expectation) matches(method string, requestUrl string, requestBody interface{}) bool {
41+
// this is a very simple "must match 100%" for the first version
42+
urlMatches := e.Request.Url == requestUrl
43+
methodMatches := e.Request.Method == method
44+
bodyMatches := requestBodyAsString(e.Request.Body) == requestBodyAsString(requestBody)
45+
46+
return urlMatches && methodMatches && bodyMatches
47+
}
48+
49+
func requestBodyAsString(requestBody interface{}) string {
50+
if requestBody == nil {
51+
return ""
52+
}
53+
if asCustom, ok := requestBody.(aurestclientapi.CustomRequestBody); ok {
54+
if b, err := io.ReadAll(asCustom.BodyReader); err == nil {
55+
return string(b)
56+
} else {
57+
return fmt.Sprintf("ERROR: %s", err.Error())
58+
}
59+
}
60+
if asString, ok := requestBody.(string); ok {
61+
return asString
62+
}
63+
if asUrlValues, ok := requestBody.(url.Values); ok {
64+
asString := asUrlValues.Encode()
65+
return asString
66+
}
67+
68+
marshalled, err := json.Marshal(requestBody)
69+
if err != nil {
70+
return fmt.Sprintf("ERROR: %s", err.Error())
71+
}
72+
return string(marshalled)
73+
}
74+
75+
func headersSortedAsString(spec http.Header) string {
76+
var result strings.Builder
77+
78+
sortedKeys := make([]string, 0)
79+
for k, _ := range spec {
80+
sortedKeys = append(sortedKeys, k)
81+
}
82+
sort.Strings(sortedKeys)
83+
84+
for _, k := range sortedKeys {
85+
result.WriteString(fmt.Sprintf("%s: ", k))
86+
for _, v := range spec[k] {
87+
result.WriteString(fmt.Sprintf("%s ", v))
88+
}
89+
}
90+
return result.String()
91+
}
92+
93+
func New() (aurestclientapi.Client, *VerifierImpl) {
94+
instance := &VerifierImpl{
95+
expectations: make([]Expectation, 0),
96+
}
97+
return instance, instance
98+
}
99+
100+
func (c *VerifierImpl) Perform(ctx context.Context, method string, requestUrl string, requestBody interface{}, response *aurestclientapi.ParsedResponse) error {
101+
expected, err := c.currentExpectation(method, requestUrl, requestBody)
102+
if err != nil {
103+
return err
104+
}
105+
106+
if expected.Response.Error != nil {
107+
return expected.Response.Error
108+
}
109+
110+
mockResponse := expected.Response.Response
111+
112+
response.Header = mockResponse.Header
113+
response.Status = mockResponse.Status
114+
response.Time = mockResponse.Time
115+
if response.Body != nil && mockResponse.Body != nil {
116+
// copy over through json round trip
117+
marshalled, _ := json.Marshal(mockResponse.Body)
118+
_ = json.Unmarshal(marshalled, response.Body)
119+
}
120+
121+
return nil
122+
}
123+
124+
func (c *VerifierImpl) currentExpectation(method string, requestUrl string, requestBody interface{}) (Expectation, error) {
125+
for i, e := range c.expectations {
126+
if !e.Matched {
127+
if e.matches(method, requestUrl, requestBody) {
128+
c.expectations[i].Matched = true
129+
return e, nil
130+
} else {
131+
if c.firstUnexpected == nil {
132+
c.firstUnexpected = &Request{
133+
Name: fmt.Sprintf("unmatched expectation %d - %s", i+1, e.Request.Name),
134+
Method: method,
135+
Header: nil, // not currently available
136+
Url: requestUrl,
137+
Body: requestBody,
138+
}
139+
}
140+
return Expectation{}, fmt.Errorf("unmatched expectation %d - %s", i+1, e.Request.Name)
141+
}
142+
}
143+
}
144+
145+
if c.firstUnexpected == nil {
146+
c.firstUnexpected = &Request{
147+
Name: fmt.Sprintf("no expectations remaining - unexpected request at end"),
148+
Method: method,
149+
Header: nil, // not currently available
150+
Url: requestUrl,
151+
Body: requestBody,
152+
}
153+
}
154+
return Expectation{}, errors.New("no expectations remaining - unexpected request at end")
155+
}
156+
157+
func (c *VerifierImpl) AddExpectation(requestMatcher Request, response aurestclientapi.ParsedResponse, err error) {
158+
c.expectations = append(c.expectations, Expectation{
159+
Request: requestMatcher,
160+
Response: ResponseOrError{
161+
Response: response,
162+
Error: err,
163+
},
164+
})
165+
}
166+
167+
func (c *VerifierImpl) FirstUnexpectedOrNil() *Request {
168+
return c.firstUnexpected
169+
}

0 commit comments

Comments
 (0)