Skip to content

Commit

Permalink
Handle non-flattened keys when comparing source
Browse files Browse the repository at this point in the history
  • Loading branch information
lahsivjar committed Jun 7, 2024
1 parent d8f85a6 commit 960485e
Showing 1 changed file with 9 additions and 5 deletions.
14 changes: 9 additions & 5 deletions pkg/approvaltest/approvals.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ func ApproveEvents(t testing.TB, name string, hits []espoll.SearchHit, dynamic .
for i, hit := range hits {
sources[i] = hit.RawSource
}
rewriteDynamic(t, sources, dynamic...)
rewriteDynamic(t, sources, false, dynamic...)
// Rewrite dynamic fields and sort them for repeatable diffs.
sort.Slice(sources, func(i, j int) bool {
return compareDocumentFields(sources[i], sources[j]) < 0
Expand All @@ -85,16 +85,18 @@ func ApproveFields(t testing.TB, name string, hits []espoll.SearchHit, dynamic .
fields[i] = hit.RawFields
}
// Rewrite dynamic fields and sort them for repeatable diffs.
rewriteDynamic(t, fields, dynamic...)
rewriteDynamic(t, fields, true, dynamic...)
sort.Slice(fields, func(i, j int) bool {
return compareDocumentFields(fields[i], fields[j]) < 0
})
approveFields(t, filepath.Join("approvals", name), fields)
}

// rewriteDynamic rewrites all dynamic fields to have a known value, so dynamic
// fields don't affect diffs.
func rewriteDynamic(t testing.TB, srcs [][]byte, dynamic ...string) {
// fields don't affect diffs. The flattenedKeys parameter defines how the
// field should be queried in the source, if flattenedKeys is passed as true
// then the source will be queried for the dynamic fields as flattened keys.
func rewriteDynamic(t testing.TB, srcs [][]byte, flattenedKeys bool, dynamic ...string) {
t.Helper()

// Fields generated by the server (e.g. observer.*)
Expand All @@ -113,7 +115,9 @@ func rewriteDynamic(t testing.TB, srcs [][]byte, dynamic ...string) {

for i := range srcs {
for _, field := range dynamic {
field = strings.ReplaceAll(field, ".", "\\.")
if flattenedKeys {
field = strings.ReplaceAll(field, ".", "\\.")
}
existing := gjson.GetBytes(srcs[i], field)
if !existing.Exists() {
continue
Expand Down

0 comments on commit 960485e

Please sign in to comment.