Skip to content

Commit

Permalink
custom matcher
Browse files Browse the repository at this point in the history
  • Loading branch information
gemmahou committed Mar 15, 2024
1 parent 49cc6df commit afc9521
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 17 deletions.
2 changes: 1 addition & 1 deletion config/tests/samples/create/harness.go
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,7 @@ func NewHarness(ctx context.Context, t *testing.T) *Harness {
testName := strings.ReplaceAll(t.Name(), "/", "_")
opts := &recorder.Options{
CassetteName: filepath.Join(dir, testName),
Mode: recorder.ModeReplayOnly,
Mode: recorder.ModeRecordOnly,
RealTransport: ret.Transport,
}
r, err := recorder.NewWithOptions(opts)
Expand Down
48 changes: 32 additions & 16 deletions tests/e2e/unified_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,14 @@
package e2e

import (
"bytes"
"context"
"encoding/json"
"fmt"
"gopkg.in/dnaeon/go-vcr.v3/cassette"
"gopkg.in/dnaeon/go-vcr.v3/recorder"
"io"
"io/ioutil"
"k8s.io/klog/v2"
"net/http"
"os"
Expand Down Expand Up @@ -196,27 +199,40 @@ func TestAllInSeries(t *testing.T) {
}
h.VCRRecorder.AddHook(hook, recorder.BeforeSaveHook)

//errorInteractionMismatch := func(request cassette.Request, field string, expected string, got string) {
// t.Errorf(
// "[VCR] Error with interaction: %s %s. Field %s does not match: expected: %s, got: %s.",
// request.Method,
// request.URL,
// field,
// expected,
// got,
// )
//}
h.VCRRecorder.SetMatcher(func(r *http.Request, i cassette.Request) bool {
// We applied BeforeSaveHook, need to modify the incoming request,
// so that incoming request matches the saved request.
modifiedURL := replaceFunc(r.URL.String())

if r.Method != i.Method {
klog.Fatalf("[VCR] Fail")
// Request saved in cassette
expected := []string{i.Method, i.URL}
// Incoming request
got := []string{r.Method, modifiedURL}

if r.Method != i.Method || modifiedURL != i.URL {
klog.Fatalf("[VCR] Request does not match: expected: %s, got: %s.",
strings.Join(expected, " "),
strings.Join(got, " "))
return false
}

if modifiedURL != i.URL {
klog.Fatalf("[VCR] Fail")
return false
// If request body exists, check body as well
if r.Body != nil && r.Body != http.NoBody {
var reqBody []byte
var err error
reqBody, err = io.ReadAll(r.Body)
if err != nil {
t.Fatal("[VCR] Failed to read request body")
}
r.Body.Close()
r.Body = ioutil.NopCloser(bytes.NewBuffer(reqBody))

modifiedBody := replaceFunc(string(reqBody))
if modifiedBody != i.Body {
klog.Fatalf("[VCR] Request body does not match: expected: %s, got: %s.",
modifiedBody,
i.Body)
return false
}
}
return true
})
Expand Down

0 comments on commit afc9521

Please sign in to comment.