on main help sign in
fix(test): improve go-vcr request matching logic
4926d2cAndrey Nering
internal/agent/recorder_test.go+15−3
@@ -58,14 +58,16 @@ func customMatcher(t *testing.T) recorder.MatcherFunc {
58 // Some providers can sometimes generate JSON requests with keys in
58 // Some providers can sometimes generate JSON requests with keys in
59 // a different order, which means a direct string comparison will fail.
59 // a different order, which means a direct string comparison will fail.
60 // Falling back to deserializing the content if we don't have a match.
60 // Falling back to deserializing the content if we don't have a match.
61− if string(reqBody) == i.Body { // hot path
61+ requestContent := normalizeLineEndings(reqBody)
62+ cassetteContent := normalizeLineEndings(i.Body)
63+ if requestContent == cassetteContent {
62 return true
64 return true
63 }
65 }
64 var content1, content2 any
66 var content1, content2 any
65− if err := json.Unmarshal(reqBody, &content1); err != nil {
67+ if err := json.Unmarshal([]byte(requestContent), &content1); err != nil {
66 return false
68 return false
67 }
69 }
68− if err := json.Unmarshal([]byte(i.Body), &content2); err != nil {
70+ if err := json.Unmarshal([]byte(cassetteContent), &content2); err != nil {
69 return false
71 return false
70 }
72 }
71 return reflect.DeepEqual(content1, content2)
73 return reflect.DeepEqual(content1, content2)
@@ -102,3 +104,13 @@ func hookRemoveHeaders(i *cassette.Interaction) error {
102 }
104 }
103 return nil
105 return nil
104}
106}
107+
108+// normalizeLineEndings does not only replace `\r\n` into `\n`,
109+// but also replaces `\\r\\n` into `\\n`. That's because we want the content
110+// inside JSON string to be replaces as well.
111+func normalizeLineEndings[T string | []byte](s T) string {
112+ str := string(s)
113+ str = strings.ReplaceAll(str, "\r\n", "\n")
114+ str = strings.ReplaceAll(str, `\r\n`, `\n`)
115+ return str
116+}