Skip to content

Commit

Permalink
Merge pull request #447 from elisasre/feat/must-encode
Browse files Browse the repository at this point in the history
Add must json encoding
  • Loading branch information
heppu authored Nov 25, 2024
2 parents 3bb1889 + 6d6c378 commit 4e89c9f
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
12 changes: 12 additions & 0 deletions v2/must/must.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,18 @@ func Unmarshal(t T, data []byte, v interface{}) {
require.NoError(t, json.Unmarshal(data, v))
}

func EncodeJSON(t T, w io.Writer, v interface{}) {
t.Helper()
err := json.NewEncoder(w).Encode(v)
require.NoError(t, err)
}

func DecodeJSON(t T, r io.Reader, v interface{}) {
t.Helper()
err := json.NewDecoder(r).Decode(v)
require.NoError(t, err)
}

func ReadAll(t T, r io.Reader) []byte {
t.Helper()
b, err := io.ReadAll(r)
Expand Down
13 changes: 13 additions & 0 deletions v2/must/must_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,19 @@ func TestHappyPath(t *testing.T) {
require.Equal(t, body, data)
}

func TestMustEncodeJSON(t *testing.T) {
buf := &bytes.Buffer{}
noFail(t, func(mt *mockT) { must.EncodeJSON(mt, buf, "hello") })
assert.JSONEq(t, `"hello"`, buf.String())
}

func TestMustDecodeJSON(t *testing.T) {
buf := bytes.NewReader([]byte(`"world"`))
var s string
noFail(t, func(mt *mockT) { must.DecodeJSON(mt, buf, &s) })
assert.Equal(t, "world", s)
}

type mockT struct {
failed bool
msg string
Expand Down

0 comments on commit 4e89c9f

Please sign in to comment.