From e4f809f26eba15071f8230ce7270aa5cf0a7cc19 Mon Sep 17 00:00:00 2001 From: Peter Guy Date: Fri, 15 Sep 2023 09:08:44 -0700 Subject: [PATCH] Compare JSON test output semantically instead of as strings. (#56667) * Compare JSON test output semantically instead of as strings. Frustrated by your tests failing due to inconsequential whitespace? Fret no more! Introducing semantic comparison of JSON test results, using state-of-the art tools! * bazel configure --- internal/testutil/BUILD.bazel | 5 ++++- internal/testutil/golden.go | 28 +++++++++++++++++++++++----- 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/internal/testutil/BUILD.bazel b/internal/testutil/BUILD.bazel index 998bbc5cbc4..58fb9509274 100644 --- a/internal/testutil/BUILD.bazel +++ b/internal/testutil/BUILD.bazel @@ -8,5 +8,8 @@ go_library( ], importpath = "github.com/sourcegraph/sourcegraph/internal/testutil", visibility = ["//:__subpackages__"], - deps = ["@com_github_google_go_cmp//cmp"], + deps = [ + "@com_github_google_go_cmp//cmp", + "@com_github_stretchr_testify//require", + ], ) diff --git a/internal/testutil/golden.go b/internal/testutil/golden.go index 3a0b4a2d234..9c603d2e598 100644 --- a/internal/testutil/golden.go +++ b/internal/testutil/golden.go @@ -7,18 +7,17 @@ import ( "testing" "github.com/google/go-cmp/cmp" + "github.com/stretchr/testify/require" ) func AssertGolden(t testing.TB, path string, update bool, want any) { t.Helper() - data := marshal(t, want) - if update { if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { t.Fatalf("failed to update golden file %q: %s", path, err) } - if err := os.WriteFile(path, data, 0o640); err != nil { + if err := os.WriteFile(path, marshal(t, want), 0o640); err != nil { t.Fatalf("failed to update golden file %q: %s", path, err) } } @@ -28,8 +27,27 @@ func AssertGolden(t testing.TB, path string, update bool, want any) { t.Fatalf("failed to read golden file %q: %s", path, err) } - if diff := cmp.Diff(string(golden), string(data)); diff != "" { - t.Errorf("(-want, +got):\n%s", diff) + compare(t, golden, want) +} + +func compare(t testing.TB, got []byte, want any) { + t.Helper() + + switch wantIs := want.(type) { + case string: + if diff := cmp.Diff(string(got), wantIs); diff != "" { + t.Errorf("(-want, +got):\n%s", diff) + } + case []byte: + if diff := cmp.Diff(string(got), string(wantIs)); diff != "" { + t.Errorf("(-want, +got):\n%s", diff) + } + default: + wantBytes, err := json.Marshal(want) + if err != nil { + t.Fatal(err) + } + require.JSONEq(t, string(got), string(wantBytes)) } }