Skip to content
This repository was archived by the owner on Mar 23, 2025. It is now read-only.

Commit f95505a

Browse files
committed
update tests
1 parent ad4ab70 commit f95505a

File tree

3 files changed

+292
-15
lines changed

3 files changed

+292
-15
lines changed

httpvcr.go

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package httpvcr
22

3-
import "net/http"
3+
import (
4+
"net/http"
5+
)
46

57
type Mode uint32
68

@@ -48,6 +50,9 @@ func New(cassetteName string, opts ...Options) *HTTPVCR {
4850
}
4951
}
5052

53+
// Start starts a VCR session with the given cassette name.
54+
// Records episodes if the cassette file does not exists.
55+
// Otherwise plays back recorded episodes.
5156
func (v *HTTPVCR) Start() {
5257
if v.mode != ModeStopped {
5358
panic("httpvcr: session already started!")
@@ -66,20 +71,26 @@ func (v *HTTPVCR) Start() {
6671
}
6772
}
6873

74+
// Stop stops the VCR session and writes the cassette file (when recording)
6975
func (v *HTTPVCR) Stop() {
7076
if v.mode == ModeRecord {
7177
v.Cassette.write()
7278
}
73-
// TODO: what happens if we stop then start again?
74-
v.mode = ModeStopped
7579

76-
if v.options.HTTPDefaultOverride {
80+
if v.options.HTTPDefaultOverride { //&& v.originalTransport != nil {
7781
http.DefaultTransport = v.originalTransport
7882
}
83+
84+
v.mode = ModeStopped
7985
}
8086

8187
func (v *HTTPVCR) Mode() Mode {
82-
return v.Mode()
88+
return v.mode
89+
}
90+
91+
// FilterData allows replacement of sensitive data with a dummy-string
92+
func (v *HTTPVCR) FilterResponseBody(original string, replacement string) {
93+
v.FilterMap[original] = replacement
8394
}
8495

8596
func (v *HTTPVCR) RoundTrip(request *http.Request) (*http.Response, error) {
@@ -103,6 +114,7 @@ func (v *HTTPVCR) RoundTrip(request *http.Request) (*http.Response, error) {
103114

104115
e := episode{Request: vcrReq, Response: vcrRes}
105116
v.Cassette.Episodes = append(v.Cassette.Episodes, e)
117+
106118
} else {
107119
e := v.Cassette.matchEpisode(vcrReq)
108120
vcrRes = e.Response

httpvcr_test.go

Lines changed: 265 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,266 @@
11
package httpvcr
2+
3+
import (
4+
"bytes"
5+
"encoding/base64"
6+
"fmt"
7+
"io/ioutil"
8+
"net/http"
9+
"net/http/httptest"
10+
"os"
11+
"strings"
12+
"testing"
13+
14+
"github.com/stretchr/testify/assert"
15+
)
16+
17+
var testRequestCounter = 0
18+
19+
func testBegin(t *testing.T) {
20+
// delete old fixtures
21+
err := os.RemoveAll("fixtures")
22+
assert.Nil(t, err)
23+
24+
// reset counter
25+
testRequestCounter = 0
26+
}
27+
28+
func testRequest(t *testing.T, url string, postBody *string) (*http.Response, string) {
29+
var err error
30+
var response *http.Response
31+
32+
if postBody != nil {
33+
buf := bytes.NewBufferString(*postBody)
34+
response, err = http.Post(url, "text/plain", buf)
35+
} else {
36+
response, err = http.Get(url)
37+
}
38+
assert.Nil(t, err)
39+
defer response.Body.Close()
40+
41+
body, err := ioutil.ReadAll(response.Body)
42+
assert.Nil(t, err)
43+
44+
return response, string(body)
45+
}
46+
47+
func testAllRequests(t *testing.T, urlBase string) {
48+
var body string
49+
var response *http.Response
50+
51+
response, body = testRequest(t, urlBase, nil)
52+
assert.Equal(t, "0:GET:/:''", body)
53+
assert.Equal(t, 200, response.StatusCode)
54+
assert.Equal(t, "200 OK", response.Status)
55+
assert.Equal(t, "HTTP/1.0", response.Proto)
56+
assert.Equal(t, 1, response.ProtoMajor)
57+
assert.Equal(t, 0, response.ProtoMinor)
58+
assert.Equal(t, len(body), int(response.ContentLength))
59+
assert.Equal(t, []string{"yes"}, response.Header["Test"])
60+
61+
_, body = testRequest(t, urlBase, nil)
62+
assert.Equal(t, "1:GET:/:''", body)
63+
64+
str := "Hey Buddy"
65+
response, body = testRequest(t, urlBase, &str)
66+
assert.Equal(t, "2:POST:/:'Hey Buddy'", body)
67+
assert.Equal(t, len(body), int(response.ContentLength))
68+
69+
multilineStr := "abc\ndef\n"
70+
_, body = testRequest(t, urlBase, &multilineStr)
71+
assert.Equal(t, "3:POST:/:'abc\ndef\n'", body)
72+
73+
_, body = testRequest(t, urlBase+"/modme", &str)
74+
assert.Equal(t, "4:POST:/modme:'moddedString'", body)
75+
76+
str = "secret-key"
77+
_, body = testRequest(t, urlBase, &str)
78+
assert.Equal(t, "5:POST:/:'secret-key'", body)
79+
80+
}
81+
82+
func testServer() *httptest.Server {
83+
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
84+
header := w.Header()
85+
header["Test"] = []string{"yes"}
86+
87+
body, _ := ioutil.ReadAll(r.Body)
88+
fmt.Fprintf(w, "%d:%s:%s:'%s'", testRequestCounter, r.Method, r.URL.Path, body)
89+
testRequestCounter++
90+
}))
91+
}
92+
93+
func requestMod(request *http.Request) {
94+
if request.URL.Path == "/modme" {
95+
ModifyHTTPRequestBody(request, func(body string) string {
96+
return strings.Replace(string(body), "Hey Buddy", "moddedString", 1)
97+
})
98+
}
99+
}
100+
101+
func TestVCR(t *testing.T) {
102+
testBegin(t)
103+
104+
ts := testServer()
105+
defer ts.Close()
106+
107+
vcr := New("test_cassette")
108+
vcr.FilterResponseBody("secret-key", "dummy-key")
109+
vcr.RequestModifier = requestMod
110+
111+
vcr.Start()
112+
assert.Equal(t, ModeRecord, vcr.Mode())
113+
testAllRequests(t, ts.URL)
114+
vcr.Stop()
115+
116+
// this only works because the key is the only body content.
117+
// otherwise the base64 alignment would be off.
118+
data, _ := ioutil.ReadFile("fixtures/vcr/test_cassette.json")
119+
assert.Contains(t, string(data), base64.StdEncoding.EncodeToString([]byte("dummy-key")))
120+
assert.NotContains(t, string(data), base64.StdEncoding.EncodeToString([]byte("secret-key")))
121+
122+
vcr.Start()
123+
assert.Equal(t, ModeReplay, vcr.Mode())
124+
testAllRequests(t, ts.URL)
125+
vcr.Stop()
126+
}
127+
128+
func TestNoSession(t *testing.T) {
129+
testBegin(t)
130+
131+
ts := testServer()
132+
defer ts.Close()
133+
134+
_, body := testRequest(t, ts.URL, nil)
135+
assert.Equal(t, "0:GET:/:''", body)
136+
}
137+
138+
func TestNoEpisodesLeft(t *testing.T) {
139+
testBegin(t)
140+
141+
defer func() {
142+
assert.Equal(t, "httpvcr: no more episodes!", recover())
143+
}()
144+
145+
vcr := New("test_cassette")
146+
vcr.Start()
147+
vcr.Stop()
148+
149+
vcr.Start()
150+
defer vcr.Stop()
151+
testRequest(t, "http://1.2.3.4", nil)
152+
}
153+
154+
func TestEpisodesDoNotMatch(t *testing.T) {
155+
testBegin(t)
156+
157+
ts := testServer()
158+
defer ts.Close()
159+
160+
vcr := New("test_cassette")
161+
assert.Equal(t, ModeStopped, vcr.Mode())
162+
vcr.Start()
163+
assert.Equal(t, ModeRecord, vcr.Mode())
164+
testRequest(t, ts.URL, nil)
165+
vcr.Stop()
166+
167+
// Method mismatch
168+
func() {
169+
vcr.Start()
170+
defer vcr.Stop()
171+
172+
defer func() {
173+
assert.Equal(t, fmt.Sprintf("httpvcr: problem with episode for POST %s\n episode Method does not match:\n expected: GET\n but got: POST", ts.URL), recover())
174+
}()
175+
176+
body := ""
177+
testRequest(t, ts.URL, &body)
178+
}()
179+
180+
// URL mismatch
181+
func() {
182+
otherURL := ts.URL + "/abc"
183+
defer func() {
184+
assert.Equal(t, fmt.Sprintf("httpvcr: problem with episode for GET %s\n episode URL does not match:\n expected: %v\n but got: %v", otherURL, ts.URL, otherURL), recover())
185+
}()
186+
187+
vcr.Start()
188+
defer vcr.Stop()
189+
testRequest(t, otherURL, nil)
190+
}()
191+
192+
func() {
193+
defer func() {
194+
assert.Equal(t, fmt.Sprintf("httpvcr: problem with episode for POST %s\n episode Body does not match:\n expected: foo\n but got: bar", ts.URL), recover())
195+
}()
196+
197+
body := "foo"
198+
199+
vcr = New("test_cassette2")
200+
201+
vcr.Start()
202+
testRequest(t, ts.URL, &body)
203+
vcr.Stop()
204+
205+
vcr.Start()
206+
defer vcr.Stop()
207+
body = "bar"
208+
testRequest(t, ts.URL, &body)
209+
}()
210+
}
211+
212+
func TestOriginalRoundTripErrors(t *testing.T) {
213+
testBegin(t)
214+
215+
vcr := New("test_cassette")
216+
vcr.Start()
217+
defer vcr.Stop()
218+
219+
_, err := http.Get("xhttp://foo")
220+
assert.EqualError(t, err, "Get xhttp://foo: unsupported protocol scheme \"xhttp\"")
221+
}
222+
223+
func TestFileWriteError(t *testing.T) {
224+
testBegin(t)
225+
226+
defer func() {
227+
assert.Equal(t, recover(), "httpvcr: cannot write cassette file!")
228+
}()
229+
230+
vcr := New("test")
231+
vcr.Start()
232+
defer vcr.Stop()
233+
234+
err := os.MkdirAll("fixtures/vcr/test.json", 0755)
235+
assert.Nil(t, err)
236+
}
237+
238+
func TestFileParseError(t *testing.T) {
239+
testBegin(t)
240+
241+
defer func() {
242+
assert.Equal(t, recover(), "httpvcr: cannot parse json!")
243+
}()
244+
245+
os.MkdirAll("fixtures/vcr", 0755)
246+
err := ioutil.WriteFile("fixtures/vcr/test.json", []byte("{[}"), 0644)
247+
assert.Nil(t, err)
248+
249+
vcr := New("test")
250+
vcr.Start()
251+
vcr.Stop()
252+
}
253+
254+
// func TestStartTwice(t *testing.T) {
255+
// testBegin(t)
256+
257+
// defer func() {
258+
// assert.Equal(t, recover(), "httpvcr: session already started!")
259+
// }()
260+
261+
// vcr := New("test")
262+
// vcr.Start()
263+
// vcr.Start()
264+
265+
// vcr.Stop()
266+
// }

util_test.go

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,33 +6,33 @@ import (
66
"net/http"
77
"testing"
88

9-
"github.com/stretchr/testify/require"
9+
"github.com/stretchr/testify/assert"
1010
)
1111

1212
func TestModifyHTTPRequestBody(t *testing.T) {
1313
req, err := http.NewRequest("GET", "/", bytes.NewBufferString("abc"))
14-
require.Nil(t, err)
15-
require.Equal(t, int64(3), req.ContentLength)
14+
assert.Nil(t, err)
15+
assert.Equal(t, int64(3), req.ContentLength)
1616

1717
ModifyHTTPRequestBody(req, func(input string) string {
18-
require.Equal(t, input, "abc")
18+
assert.Equal(t, input, "abc")
1919
return "foofoo"
2020
})
2121

22-
require.Equal(t, int64(6), req.ContentLength)
22+
assert.Equal(t, int64(6), req.ContentLength)
2323
body, _ := ioutil.ReadAll(req.Body)
24-
require.Equal(t, "foofoo", string(body))
24+
assert.Equal(t, "foofoo", string(body))
2525
}
2626

2727
func TestModifyHTTPRequestBodyWithNilBody(t *testing.T) {
2828
req, err := http.NewRequest("GET", "/", nil)
29-
require.Nil(t, err)
30-
require.Equal(t, int64(0), req.ContentLength)
29+
assert.Nil(t, err)
30+
assert.Equal(t, int64(0), req.ContentLength)
3131

3232
ModifyHTTPRequestBody(req, func(input string) string {
3333
return "foofoo"
3434
})
3535

36-
require.Equal(t, int64(0), req.ContentLength)
37-
require.Equal(t, req.Body, nil)
36+
assert.Equal(t, int64(0), req.ContentLength)
37+
assert.Equal(t, req.Body, nil)
3838
}

0 commit comments

Comments
 (0)