Skip to content

Commit

Permalink
Improve example test for middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
calvinmclean authored and dnaeon committed Aug 19, 2024
1 parent 4e4a789 commit 98b2115
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 43 deletions.
32 changes: 17 additions & 15 deletions examples/fixtures/middleware.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ interactions:
content_length: 0
transfer_encoding: []
trailer: {}
host: 127.0.0.1:60761
remote_addr: 127.0.0.1:60762
host: ""
remote_addr: ""
request_uri: /request1
body: ""
form: {}
Expand All @@ -37,7 +37,7 @@ interactions:
- VALUE
status: 200 OK
code: 200
duration: 42ns
duration: 0s
- id: 1
request:
proto: HTTP/1.1
Expand All @@ -46,17 +46,17 @@ interactions:
content_length: 0
transfer_encoding: []
trailer: {}
host: 127.0.0.1:60761
remote_addr: 127.0.0.1:60763
request_uri: /request2
host: ""
remote_addr: ""
request_uri: /request2?query=example
body: ""
form: {}
headers:
Accept-Encoding:
- gzip
User-Agent:
- Go-http-client/1.1
url: http://go-vcr/request2
url: http://go-vcr/request2?query=example
method: GET
response:
proto: HTTP/1.1
Expand All @@ -66,15 +66,17 @@ interactions:
trailer: {}
content_length: -1
uncompressed: false
body: OK
body: |-
query=example
OK
headers:
Content-Type:
- text/plain; charset=utf-8
Key:
- VALUE
status: 200 OK
code: 200
duration: 41ns
duration: 0s
- id: 2
request:
proto: HTTP/1.1
Expand All @@ -83,8 +85,8 @@ interactions:
content_length: 9
transfer_encoding: []
trailer: {}
host: 127.0.0.1:60761
remote_addr: 127.0.0.1:60764
host: ""
remote_addr: ""
request_uri: /postform
body: key=value
form:
Expand Down Expand Up @@ -117,7 +119,7 @@ interactions:
- VALUE
status: 200 OK
code: 200
duration: 375ns
duration: 0s
- id: 3
request:
proto: HTTP/1.1
Expand All @@ -126,8 +128,8 @@ interactions:
content_length: 15
transfer_encoding: []
trailer: {}
host: 127.0.0.1:60761
remote_addr: 127.0.0.1:60765
host: ""
remote_addr: ""
request_uri: /postdata
body: '{"key":"value"}'
form: {}
Expand Down Expand Up @@ -158,4 +160,4 @@ interactions:
- VALUE
status: 200 OK
code: 200
duration: 125ns
duration: 0s
72 changes: 44 additions & 28 deletions examples/middleware_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,43 +14,31 @@ import (

func TestMiddleware(t *testing.T) {
cassetteName := "fixtures/middleware"
createHandler := func(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")

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
}

// 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) {
recorder, err := recorder.NewWithOptions(&recorder.Options{
CassetteName: cassetteName,
Mode: recorder.ModeRecordOnly,
BlockRealTransportUnsafeMethods: false,
rec, err := recorder.NewWithOptions(&recorder.Options{
CassetteName: cassetteName,
Mode: recorder.ModeRecordOnly,
SkipRequestLatency: true,
})
if err != nil {
t.Errorf("error creating recorder: %v", err)
}

// Use a BeforeSaveHook to remove host, remote_addr, and duration
// since they change whenever the test runs
rec.AddHook(func(i *cassette.Interaction) error {
i.Request.Host = ""
i.Request.RemoteAddr = ""
i.Response.Duration = 0
return nil
}, recorder.BeforeSaveHook)

// Create the server handler with recorder middleware
handler := createHandler(recorder.Middleware)
defer recorder.Stop()
handler := createHandler(rec.Middleware)
defer rec.Stop()

server := httptest.NewServer(handler)
defer server.Close()
Expand All @@ -60,7 +48,7 @@ func TestMiddleware(t *testing.T) {
t.Errorf("error making request: %v", err)
}

_, err = http.Get(server.URL + "/request2")
_, err = http.Get(server.URL + "/request2?query=example")
if err != nil {
t.Errorf("error making request: %v", err)
}
Expand All @@ -80,3 +68,31 @@ func TestMiddleware(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
}

0 comments on commit 98b2115

Please sign in to comment.