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
This commit is contained in:
Peter Guy 2023-09-15 09:08:44 -07:00 committed by GitHub
parent 2e771ee25b
commit e4f809f26e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 27 additions and 6 deletions

View File

@ -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",
],
)

View File

@ -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))
}
}