Skip to content
This repository has been archived by the owner on Jun 12, 2024. It is now read-only.

Commit

Permalink
Implement JSONEq that allows matches on empty string (#75)
Browse files Browse the repository at this point in the history
**What**
- To simplify some of the tests checks, it can be helpful to allow
  matches on two empty strings, even though neither is valid json.
  Specifically this helps when testing apis that can return errors
  and 204 empty body.

Signed-off-by: Lucas Roesler <[email protected]>
  • Loading branch information
LucasRoesler authored Dec 9, 2020
1 parent 717f5f2 commit 5275a1f
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 0 deletions.
26 changes: 26 additions & 0 deletions pkg/testing/json.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package testing

import (
"github.com/stretchr/testify/require"
)

type tHelper interface {
Helper()
}

// JSONEq asserts that two JSON strings are equivalent or both empty.
//
// require.JSONEq(t, "", "")
// or
// require.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`)
func JSONEq(t require.TestingT, expected string, actual string, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
}
// handle empty json
if expected == actual && expected == "" {
return
}

require.JSONEq(t, expected, actual, msgAndArgs...)
}
55 changes: 55 additions & 0 deletions pkg/testing/json_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package testing

import (
"testing"

"github.com/stretchr/testify/require"
)

func TestJSONEq(t *testing.T) {

validCases := []struct {
name string
expected string
got string
}{
{"valid on empty strings", "", ""},
{"handles simple reordering of keys", `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`},
}

for _, tc := range validCases {
t.Run(tc.name, func(t *testing.T) {
JSONEq(t, tc.expected, tc.got)
})
}

failureCases := []struct {
name string
expected string
got string
}{
{"failure on empty string and non-empty string", "", `{"hello": "world", "foo": "bar"}`},
{"handles json mismatch", `{"hello": "world"}`, `{"foo": "bar", "hello": "world"}`},
}

for _, tc := range failureCases {
t.Run(tc.name, func(t *testing.T) {
mt := new(MockT)
JSONEq(mt, tc.expected, tc.got)

require.True(t, mt.Failed, "should fail")
})
}
}

type MockT struct {
Failed bool
}

func (t *MockT) FailNow() {
t.Failed = true
}

func (t *MockT) Errorf(format string, args ...interface{}) {
_, _ = format, args
}

0 comments on commit 5275a1f

Please sign in to comment.