mirror of
https://github.com/sourcegraph/sourcegraph.git
synced 2026-02-06 16:51:55 +00:00
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:
parent
2e771ee25b
commit
e4f809f26e
@ -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",
|
||||
],
|
||||
)
|
||||
|
||||
@ -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))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user