forked from dnaeon/go-vcr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware_test.go
96 lines (80 loc) · 2.42 KB
/
middleware_test.go
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package vcr_test
import (
"bytes"
"io"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"gopkg.in/dnaeon/go-vcr.v4/pkg/cassette"
"gopkg.in/dnaeon/go-vcr.v4/pkg/recorder"
)
func TestMiddleware(t *testing.T) {
cassetteName := "fixtures/middleware"
// In a real-world scenario, the recorder will run outside of unit tests
// since you want to be able to record real application behavior
t.Run("RecordRealInteractionsWithMiddleware", func(t *testing.T) {
rec, err := recorder.New(
cassetteName,
recorder.WithMode(recorder.ModeRecordOnly),
// Use a BeforeSaveHook to remove host, remote_addr, and duration
// since they change whenever the test runs
recorder.WithHook(func(i *cassette.Interaction) error {
i.Request.Host = ""
i.Request.RemoteAddr = ""
i.Response.Duration = 0
return nil
}, recorder.BeforeSaveHook),
)
if err != nil {
t.Errorf("error creating recorder: %v", err)
}
// Create the server handler with recorder middleware
handler := createHandler(rec.HTTPMiddleware)
defer rec.Stop()
server := httptest.NewServer(handler)
defer server.Close()
_, err = http.Get(server.URL + "/request1")
if err != nil {
t.Errorf("error making request: %v", err)
}
_, err = http.Get(server.URL + "/request2?query=example")
if err != nil {
t.Errorf("error making request: %v", err)
}
_, err = http.PostForm(server.URL+"/postform", url.Values{"key": []string{"value"}})
if err != nil {
t.Errorf("error making request: %v", err)
}
_, err = http.Post(server.URL+"/postdata", "application/json", bytes.NewBufferString(`{"key":"value"}`))
if err != nil {
t.Errorf("error making request: %v", err)
}
})
t.Run("ReplayCassetteAndCompare", func(t *testing.T) {
cassette.TestServerReplay(t, cassetteName, createHandler(nil))
})
}
// createHandler will return an HTTP handler with optional middleware. It will respond to
// simple requests for testing
func createHandler(middleware func(http.Handler) http.Handler) http.Handler {
mux := http.NewServeMux()
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("KEY", "VALUE")
query := r.URL.Query().Encode()
if query != "" {
w.Write([]byte(query + "\n"))
}
body, _ := io.ReadAll(r.Body)
if len(body) > 0 {
w.Write(body)
} else {
w.Write([]byte("OK"))
}
})
if middleware != nil {
handler = middleware(handler).ServeHTTP
}
mux.Handle("/", handler)
return mux
}