-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathrecorder_test.go
More file actions
75 lines (64 loc) · 1.72 KB
/
recorder_test.go
File metadata and controls
75 lines (64 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package providertests
import (
"bytes"
"io"
"net/http"
"path/filepath"
"strings"
"testing"
"gopkg.in/dnaeon/go-vcr.v4/pkg/cassette"
"gopkg.in/dnaeon/go-vcr.v4/pkg/recorder"
)
func newRecorder(t *testing.T) *recorder.Recorder {
cassetteName := filepath.Join("testdata", t.Name())
r, err := recorder.New(
cassetteName,
recorder.WithMode(recorder.ModeRecordOnce),
recorder.WithMatcher(customMatcher(t)),
recorder.WithSkipRequestLatency(true), // disable sleep to simulate response time, makes tests faster
recorder.WithHook(hookRemoveHeaders, recorder.AfterCaptureHook),
)
if err != nil {
t.Fatalf("recorder: failed to create recorder: %v", err)
}
t.Cleanup(func() {
if err := r.Stop(); err != nil {
t.Errorf("recorder: failed to stop recorder: %v", err)
}
})
return r
}
func customMatcher(t *testing.T) recorder.MatcherFunc {
return func(r *http.Request, i cassette.Request) bool {
if r.Body == nil || r.Body == http.NoBody {
return cassette.DefaultMatcher(r, i)
}
var reqBody []byte
var err error
reqBody, err = io.ReadAll(r.Body)
if err != nil {
t.Fatalf("recorder: failed to read request body")
}
r.Body.Close()
r.Body = io.NopCloser(bytes.NewBuffer(reqBody))
return r.Method == i.Method && r.URL.String() == i.URL && string(reqBody) == i.Body
}
}
var headersToKeep = map[string]struct{}{
"accept": {},
"content-type": {},
"user-agent": {},
}
func hookRemoveHeaders(i *cassette.Interaction) error {
for k := range i.Request.Headers {
if _, ok := headersToKeep[strings.ToLower(k)]; !ok {
delete(i.Request.Headers, k)
}
}
for k := range i.Response.Headers {
if _, ok := headersToKeep[strings.ToLower(k)]; !ok {
delete(i.Response.Headers, k)
}
}
return nil
}