-
Notifications
You must be signed in to change notification settings - Fork 15
/
govcr_test.go
443 lines (364 loc) · 12.4 KB
/
govcr_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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
package govcr_test
import (
"bytes"
"fmt"
"io"
"math/rand"
"net/http"
"net/http/httptest"
"os"
"strconv"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"github.com/seborama/govcr/v15"
"github.com/seborama/govcr/v15/cassette/track"
"github.com/seborama/govcr/v15/encryption"
"github.com/seborama/govcr/v15/stats"
)
func TestNewVCR(t *testing.T) {
const cassetteName = "temp-fixtures/my.cassette.json"
_ = os.Remove(cassetteName)
defer func() { _ = os.Remove(cassetteName) }()
unit := govcr.NewVCR(govcr.NewCassetteLoader(cassetteName))
assert.NotNil(t, unit.HTTPClient())
}
func TestVCRControlPanel_NewVCR_InvalidCassette(t *testing.T) {
assert.Panics(
t,
func() {
_ = govcr.NewVCR(
govcr.NewCassetteLoader("test-fixtures/bad.cassette.json"),
)
})
}
func TestVCRControlPanel_NewVCR_ValidSimpleLongPlayCassette(t *testing.T) {
unit := govcr.NewVCR(
govcr.NewCassetteLoader("test-fixtures/good_zipped_one_track.cassette.json.gz"),
)
assert.EqualValues(t, 1, unit.NumberOfTracks())
}
func TestVCRControlPanel_NewVCR_ValidSimpleShortPlayCassette(t *testing.T) {
unit := govcr.NewVCR(
govcr.NewCassetteLoader("test-fixtures/good_one_track.cassette.json"),
)
assert.EqualValues(t, 1, unit.NumberOfTracks())
}
func TestVCRControlPanel_NewVCR_UnreadableCassette(t *testing.T) {
const cassetteName = "test-fixtures/unreadable.cassette.json"
removeUnreadableCassette(t, cassetteName)
createUnreadableCassette(t, cassetteName)
assert.Panics(
t,
func() {
_ = govcr.NewVCR(
govcr.NewCassetteLoader(cassetteName),
)
})
removeUnreadableCassette(t, cassetteName)
}
func createUnreadableCassette(t *testing.T, name string) {
t.Helper()
err := os.WriteFile(name, nil, 0o111)
require.NoError(t, err)
}
func removeUnreadableCassette(t *testing.T, name string) {
t.Helper()
err := os.Chmod(name, 0o711)
if os.IsNotExist(err) {
return
}
require.NoError(t, err)
err = os.Remove(name)
require.NoError(t, err)
}
func TestVCRControlPanel_HTTPClient(t *testing.T) {
vcr := govcr.NewVCR(govcr.NewCassetteLoader("./temp-fixtures/TestVCRControlPanel_HTTPClient.cassette"))
unit := vcr.HTTPClient()
assert.IsType(t, (*http.Client)(nil), unit)
}
func TestSetCrypto(t *testing.T) {
testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = fmt.Fprintf(w, "Hello: %d\n", rand.Intn(1e9))
}))
const cassetteName = "./temp-fixtures/TestSetCrypto.cassette"
_ = os.Remove(cassetteName)
// first, create an unencrypted cassette
vcr := govcr.NewVCR(govcr.NewCassetteLoader(cassetteName))
// add a track to the cassette to trigger its creation in the first place
resp, err := vcr.HTTPClient().Get(testServer.URL)
require.NoError(t, err)
_ = resp.Body.Close()
assert.Equal(t, "not encrypted", getCassetteCrypto(cassetteName))
// encrypt cassette with AESGCM
err = vcr.SetCipher(
encryption.NewAESGCMWithRandomNonceGenerator,
"test-fixtures/TestSetCrypto.1.key",
)
require.NoError(t, err)
assert.Equal(t, "aesgcm", getCassetteCrypto(cassetteName))
// re-encrypt cassette with ChaCha20Poly1305
err = vcr.SetCipher(
encryption.NewChaCha20Poly1305WithRandomNonceGenerator,
"test-fixtures/TestSetCrypto.2.key",
)
require.NoError(t, err)
assert.Equal(t, "chacha20poly1305", getCassetteCrypto(cassetteName))
// lastly, attempt to decrypt cassette - this is not permitted
err = vcr.SetCipher(nil, "")
require.Error(t, err)
}
func getCassetteCrypto(cassetteName string) string {
data, err := os.ReadFile(cassetteName)
if err != nil {
panic(err)
}
marker := "$ENC:V2$"
if !bytes.HasPrefix(data, []byte(marker)) {
return "not encrypted"
}
pos := len(marker)
cipherNameLen := int(data[len(marker)])
return string(data[pos+1 : pos+1+cipherNameLen])
}
type GoVCRTestSuite struct {
suite.Suite
testServer *httptest.Server
}
func TestGoVCRTestSuite(t *testing.T) {
suite.Run(t, new(GoVCRTestSuite))
}
func (ts *GoVCRTestSuite) SetupTest() {
func() {
counter := 0
ts.testServer = httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
counter++
if r.URL.Query().Get("crash") == "1" {
panic("simulate a server crash")
}
iQuery := r.URL.Query().Get("i")
_, _ = fmt.Fprintf(w, "Hello, server responds '%d' to query '%s'", counter, iQuery)
}))
}()
}
func (ts *GoVCRTestSuite) TearDownTest() {
ts.testServer.Close()
}
type action int
const (
actionKeepCassette = iota
actionDeleteCassette
)
func (ts *GoVCRTestSuite) newVCR(cassetteName string, a action) *govcr.ControlPanel {
if a == actionDeleteCassette {
_ = os.Remove(cassetteName)
}
testServerClient := ts.testServer.Client()
testServerClient.Timeout = 3 * time.Second
return govcr.NewVCR(
govcr.NewCassetteLoader(cassetteName),
govcr.WithClient(testServerClient),
)
}
func (ts *GoVCRTestSuite) TestVCR_ReadOnlyMode() {
const k7Name = "temp-fixtures/TestGoVCRTestSuite.TestVCR_ReadOnlyMode.cassette.json"
vcr := ts.newVCR(k7Name, actionDeleteCassette)
vcr.SetReadOnlyMode(true)
resp, err := vcr.HTTPClient().Get(ts.testServer.URL)
ts.Require().NoError(err)
ts.Require().NotNil(resp)
defer func() { _ = resp.Body.Close() }()
expectedStats := &stats.Stats{
TotalTracks: 0,
TracksLoaded: 0,
TracksRecorded: 0,
TracksPlayed: 0,
}
ts.EqualValues(expectedStats, vcr.Stats())
}
func (ts *GoVCRTestSuite) TestVCR_LiveOnlyMode() {
const k7Name = "temp-fixtures/TestGoVCRTestSuite.TestVCR_LiveOnlyMode.cassette.json"
// 1st execution of set of calls
vcr := ts.newVCR(k7Name, actionDeleteCassette)
vcr.SetLiveOnlyMode()
vcr.SetRequestMatchers(alwaysMatchRequest) // ensure always matching
ts.makeHTTPCalls_WithSuccess(vcr.HTTPClient(), 0)
expectedStats := &stats.Stats{
TotalTracks: 2,
TracksLoaded: 0,
TracksRecorded: 2,
TracksPlayed: 0,
}
ts.EqualValues(expectedStats, vcr.Stats())
ts.Require().FileExists(k7Name)
// 2nd execution of set of calls
vcr = ts.newVCR(k7Name, actionKeepCassette)
vcr.SetLiveOnlyMode()
vcr.SetRequestMatchers(alwaysMatchRequest) // ensure always matching
ts.makeHTTPCalls_WithSuccess(vcr.HTTPClient(), 2) // as we're making live requests, the sever keeps on increasing the counter
expectedStats = &stats.Stats{
TotalTracks: 4,
TracksLoaded: 2,
TracksRecorded: 2,
TracksPlayed: 0,
}
ts.EqualValues(expectedStats, vcr.Stats())
}
func (ts *GoVCRTestSuite) TestVCR_OfflineMode() {
const k7Name = "temp-fixtures/TestGoVCRTestSuite.TestVCR_OfflineMode.cassette.json"
// 1st execution of set of calls - populate cassette
vcr := ts.newVCR(k7Name, actionDeleteCassette)
vcr.SetRequestMatchers(alwaysMatchRequest) // ensure always matching
vcr.SetNormalMode() // get data in the cassette
ts.makeHTTPCalls_WithSuccess(vcr.HTTPClient(), 0)
expectedStats := &stats.Stats{
TotalTracks: 2,
TracksLoaded: 0,
TracksRecorded: 2,
TracksPlayed: 0,
}
ts.EqualValues(expectedStats, vcr.Stats())
ts.Require().FileExists(k7Name)
// 2nd execution of set of calls -- offline only
vcr = ts.newVCR(k7Name, actionKeepCassette)
vcr.SetOfflineMode()
ts.makeHTTPCalls_WithSuccess(vcr.HTTPClient(), 0)
expectedStats = &stats.Stats{
TotalTracks: 2,
TracksLoaded: 2,
TracksRecorded: 0,
TracksPlayed: 2,
}
ts.EqualValues(expectedStats, vcr.Stats())
// 3rd execution of set of calls -- still offline only
// we've run out of tracks on the cassette and we're in offline mode so we expect a transport error
req, err := http.NewRequest(http.MethodGet, ts.testServer.URL, nil)
ts.Require().NoError(err)
resp, err := vcr.HTTPClient().Do(req) //nolint:bodyclose
ts.Require().Error(err)
ts.Assert().Contains(err.Error(), "no track matched on cassette and offline mode is active")
ts.Assert().Nil(resp)
}
func (ts *GoVCRTestSuite) TestRoundTrip_ReplaysError() {
tt := []*struct {
name string
reqURL string
wantErr string
wantVCRErr string
}{
// NOTE: different versions of Go have variations of these actual errors - below are for Go 1.18
{
name: "should replay protocol error",
reqURL: "boom://127.1.2.3",
wantErr: `Get "boom://127.1.2.3": unsupported protocol scheme "boom"`,
wantVCRErr: `Get "boom://127.1.2.3": *errors.errorString: unsupported protocol scheme "boom"`,
},
// This test is flaky: it can return 2 different types of errors (Go 1.18)
// {
// name: "should replay request cancellation on connection failure",
// reqURL: "https://127.1.2.3",
// wantErr: `Get "https://127.1.2.3": net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers)`,
// wantVCRErr: `Get "https://127.1.2.3": *errors.errorString: net/http: request canceled while waiting for connection`,
// },
{
name: "should replay request on server crash",
reqURL: ts.testServer.URL + "?crash=1",
wantErr: `Get "` + ts.testServer.URL + `?crash=1": EOF`,
wantVCRErr: `Get "` + ts.testServer.URL + `?crash=1": *errors.errorString: EOF`,
},
}
const k7Name = "temp-fixtures/TestGoVCRTestSuite.TestRoundTrip_ReplaysError.cassette.json"
for idx, tc := range tt {
ts.T().Run(tc.name, func(t *testing.T) {
cassetteName := k7Name + fmt.Sprintf(".test_case_%d", idx)
// execute HTTP call and record on cassette
vcr := ts.newVCR(cassetteName, actionDeleteCassette)
resp, err := vcr.HTTPClient().Get(tc.reqURL) //nolint:bodyclose
ts.Require().Error(err)
ts.EqualError(err, tc.wantErr)
ts.Require().Nil(resp)
expectedStats := &stats.Stats{
TotalTracks: 1,
TracksLoaded: 0,
TracksRecorded: 1,
TracksPlayed: 0,
}
ts.EqualValues(expectedStats, vcr.Stats())
// replay from cassette
ts.Require().FileExists(cassetteName)
vcr = ts.newVCR(cassetteName, actionKeepCassette)
ts.EqualValues(1, vcr.NumberOfTracks())
resp, err = vcr.HTTPClient().Get(tc.reqURL) //nolint:bodyclose
ts.Require().Error(err)
ts.EqualError(err, tc.wantVCRErr)
ts.Require().Nil(resp)
expectedStats = &stats.Stats{
TotalTracks: 1,
TracksLoaded: 1,
TracksRecorded: 0,
TracksPlayed: 1,
}
ts.EqualValues(expectedStats, vcr.Stats())
})
}
}
func (ts *GoVCRTestSuite) TestRoundTrip_ReplaysPlainResponse() {
const k7Name = "temp-fixtures/TestGoVCRTestSuite.TestRoundTrip_ReplaysPlainResponse.cassette.json"
// 1st execution of set of calls
vcr := ts.newVCR(k7Name, actionDeleteCassette)
ts.makeHTTPCalls_WithSuccess(vcr.HTTPClient(), 0)
expectedStats := &stats.Stats{
TotalTracks: 2,
TracksLoaded: 0,
TracksRecorded: 2,
TracksPlayed: 0,
}
ts.EqualValues(expectedStats, vcr.Stats())
ts.Require().FileExists(k7Name)
// 2nd execution of set of calls (replayed with cassette reload)
vcr = ts.newVCR(k7Name, actionKeepCassette)
ts.makeHTTPCalls_WithSuccess(vcr.HTTPClient(), 0)
expectedStats = &stats.Stats{
TotalTracks: 2,
TracksLoaded: 2,
TracksRecorded: 0,
TracksPlayed: 2,
}
ts.EqualValues(expectedStats, vcr.Stats())
// 3rd execution of set of calls (replayed without cassette reload)
ts.makeHTTPCalls_WithSuccess(vcr.HTTPClient(), int(expectedStats.TotalTracks)) // as we're making live requests, the sever keeps on increasing the counter
expectedStats = &stats.Stats{
TotalTracks: 4,
TracksLoaded: 2,
TracksRecorded: 2,
TracksPlayed: 2,
}
ts.EqualValues(expectedStats, vcr.Stats())
}
func (ts *GoVCRTestSuite) makeHTTPCalls_WithSuccess(httpClient *http.Client, serverCurrentCount int) {
for i := 1; i <= 2; i++ {
req, err := http.NewRequest(http.MethodGet, ts.testServer.URL+fmt.Sprintf("?i=%d", i), nil)
ts.Require().NoError(err)
req.Header.Add("header", "value")
req.SetBasicAuth("not_a_username", "not_a_password")
resp, err := httpClient.Do(req)
ts.Require().NoError(err)
ts.Equal(http.StatusOK, resp.StatusCode)
ts.EqualValues(strconv.Itoa(38+len(strconv.Itoa(i))), resp.Header.Get("Content-Length"))
ts.EqualValues("text/plain; charset=utf-8", resp.Header.Get("Content-Type"))
ts.NotEmpty(resp.Header.Get("Date"))
ts.EqualValues(resp.Trailer, http.Header(nil))
bodyBytes, err := io.ReadAll(resp.Body)
ts.Require().NoError(err)
_ = resp.Body.Close()
ts.Equal(fmt.Sprintf("Hello, server responds '%d' to query '%d'", serverCurrentCount+i, i), string(bodyBytes))
ts.Equal(int64(38+len(strconv.Itoa(serverCurrentCount+i))), resp.ContentLength)
ts.NotNil(resp.Request)
ts.NotNil(resp.TLS)
}
}
func alwaysMatchRequest(httpRequest, trackRequest *track.Request) bool {
return true
}