-
Notifications
You must be signed in to change notification settings - Fork 0
/
vcr.go
50 lines (39 loc) · 939 Bytes
/
vcr.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
package testutils
import (
"bytes"
"io/ioutil"
"net/http"
"testing"
"github.com/dnaeon/go-vcr/cassette"
"github.com/dnaeon/go-vcr/recorder"
)
// RecordHTTP wraps tests and records all http requests made with the default
// http transport in a file with the given name. If the file exists,
// requests are replayed.
func RecordHTTP(m *testing.M, filename string) int {
t := http.DefaultTransport
rec, err := recorder.New(filename)
if err != nil {
panic(err)
}
rec.SetMatcher(func(rec *http.Request, i cassette.Request) bool {
if !cassette.DefaultMatcher(rec, i) {
return false
}
if rec.Body == nil {
return true
}
var b bytes.Buffer
if _, err := b.ReadFrom(rec.Body); err != nil {
return false
}
rec.Body = ioutil.NopCloser(&b)
return b.String() == "" || b.String() == i.Body
})
defer func() {
http.DefaultTransport = t
rec.Stop()
}()
http.DefaultTransport = rec
return m.Run()
}