Skip to content

Commit

Permalink
add hook
Browse files Browse the repository at this point in the history
  • Loading branch information
gemmahou committed Mar 12, 2024
1 parent 0c81fc3 commit e848f53
Show file tree
Hide file tree
Showing 3 changed files with 113 additions and 206 deletions.
5 changes: 4 additions & 1 deletion config/tests/samples/create/harness.go
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,10 @@ func NewHarness(ctx context.Context, t *testing.T) *Harness {
Mode: recorder.ModeRecordOnly,
RealTransport: ret.Transport,
}
r, _ := recorder.NewWithOptions(opts)
r, err := recorder.NewWithOptions(opts)
if err != nil {
t.Fatalf("creat vcr recorder failed: %v", err)
}
h.Rec = r
ret = &http.Client{Transport: h.Rec}
return ret
Expand Down
54 changes: 53 additions & 1 deletion tests/e2e/unified_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,11 @@ package e2e

import (
"context"
"encoding/json"
"fmt"
"gopkg.in/dnaeon/go-vcr.v3/cassette"
"gopkg.in/dnaeon/go-vcr.v3/recorder"
"k8s.io/klog/v2"
"os"
"path/filepath"
"strings"
Expand Down Expand Up @@ -122,12 +126,60 @@ func TestAllInSeries(t *testing.T) {

if os.Getenv("E2E_GCP_TARGET") == "vcr" {
// Stop recording after tests finish and write to cassette
vcrRecorder := h.Rec
defer func() {
err := h.Rec.Stop()
err := vcrRecorder.Stop()
if err != nil {
t.Errorf("[VCR] Failed stop vcr recorder: %v", err)
}
}()

hook := func(i *cassette.Interaction) error {
var requestHeadersToRemove = []string{
"Authorization",
"User-Agent",
}
for _, header := range requestHeadersToRemove {
delete(i.Request.Headers, header)
}

var responseHeadersToRemove = []string{
"Cache-Control",
"Server",
"Vary",
"X-Content-Type-Options",
"X-Frame-Options",
"X-Xss-Protection",
"Date",
"Etag",
}
for _, header := range responseHeadersToRemove {
delete(i.Response.Headers, header)
}

replaceFunc := func(s string) string {
result := strings.Replace(s, uniqueID, "{uniqueID}", -1)
result = strings.Replace(result, project.ProjectID, "{projectID}", -1)
return result
}

i.Request.Body = replaceFunc(i.Request.Body)
i.Response.Body = replaceFunc(i.Response.Body)
i.Request.URL = replaceFunc(i.Request.URL)

s := i.Response.Body
obj := make(map[string]any)
if err := json.Unmarshal([]byte(s), &obj); err != nil {
klog.Fatalf("error from json.Unmarshal(%q): %v", s, err)
}
toReplace, _, _ := unstructured.NestedString(obj, "user")
if len(toReplace) != 0 {
s = strings.Replace(s, toReplace, "{user}", -1)
}
i.Response.Body = s
return nil
}
vcrRecorder.AddHook(hook, recorder.BeforeSaveHook)
}

primaryResource, opt := loadFixture(project)
Expand Down
Loading

0 comments on commit e848f53

Please sign in to comment.