Skip to content

Commit

Permalink
test: add ValidJSON and ValidJSONBytes assertions
Browse files Browse the repository at this point in the history
Add heper methods that defer to Go json.Valid function for checking
a string or byte slice is valid json.

Closes #103
  • Loading branch information
shoenig committed Jan 28, 2023
1 parent 57f69f4 commit 523a131
Show file tree
Hide file tree
Showing 5 changed files with 67 additions and 0 deletions.
15 changes: 15 additions & 0 deletions internal/assertions/assertions.go
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,21 @@ func EqJSON(exp, val string) (s string) {
return
}

func ValidJSON(input string) (s string) {
return validJSON([]byte(input))
}

func ValidJSONBytes(input []byte) (s string) {
return validJSON(input)
}

func validJSON(input []byte) (s string) {
if !json.Valid([]byte(input)) {
return "expected input to be valid json\n"
}
return
}

func EqSliceFunc[A any](exp, val []A, eq func(a, b A) bool) (s string) {
lenA, lenB := len(exp), len(val)

Expand Down
12 changes: 12 additions & 0 deletions must/must.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 14 additions & 0 deletions must/must_test.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions test.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,18 @@ func EqJSON(t T, exp, val string, settings ...Setting) {
invoke(t, assertions.EqJSON(exp, val), settings...)
}

// ValidJSON asserts js is valid JSON.
func ValidJSON(t T, js string, settings ...Setting) {
t.Helper()
invoke(t, assertions.ValidJSON(js), settings...)
}

// ValidJSONBytes asserts js is valid JSON.
func ValidJSONBytes(t T, js []byte, settings ...Setting) {
t.Helper()
invoke(t, assertions.ValidJSONBytes(js))
}

// Equal asserts val.Equal(exp).
func Equal[E interfaces.EqualFunc[E]](t T, exp, val E, settings ...Setting) {
t.Helper()
Expand Down
14 changes: 14 additions & 0 deletions test_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,20 @@ func TestEqJSON_PS(t *testing.T) {
EqJSON(tc, `"one"`, `"two"`, tc.TestPostScript("eq json"))
}

func TestValidJSON(t *testing.T) {
tc := newCapture(t)
t.Cleanup(tc.assert)

ValidJSON(tc, `{"a":1, "b":}`)
}

func TestValidJSONBytes(t *testing.T) {
tc := newCapture(t)
t.Cleanup(tc.assert)

ValidJSONBytes(tc, []byte(`{"a":1, "b":}`))
}

func TestSliceEqFunc(t *testing.T) {
t.Run("length", func(t *testing.T) {
tc := newCase(t, `expected slices of same length`)
Expand Down

0 comments on commit 523a131

Please sign in to comment.