From bf024fb98591b8effb4c451973b5f222cca4009d Mon Sep 17 00:00:00 2001 From: Ainar Garipov Date: Mon, 11 Jul 2022 17:40:00 +0300 Subject: [PATCH] Pull request: aghalg: impl json.Marshaler for NullBool Updates #4735. Squashed commit of the following: commit 93a0b1dc6b668f7d9fd89d06b8f0f24dcd345356 Author: Ainar Garipov Date: Mon Jul 11 17:02:36 2022 +0300 aghalg: impl json.Marshaler for NullBool --- internal/aghalg/nullbool.go | 8 ++++++ internal/aghalg/nullbool_test.go | 46 ++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/internal/aghalg/nullbool.go b/internal/aghalg/nullbool.go index 3c5633e3..01a8c974 100644 --- a/internal/aghalg/nullbool.go +++ b/internal/aghalg/nullbool.go @@ -40,6 +40,14 @@ func BoolToNullBool(cond bool) (nb NullBool) { return NBFalse } +// type check +var _ json.Marshaler = NBNull + +// MarshalJSON implements the json.Marshaler interface for NullBool. +func (nb NullBool) MarshalJSON() (b []byte, err error) { + return []byte(nb.String()), nil +} + // type check var _ json.Unmarshaler = (*NullBool)(nil) diff --git a/internal/aghalg/nullbool_test.go b/internal/aghalg/nullbool_test.go index 0fe7f203..8096f1069 100644 --- a/internal/aghalg/nullbool_test.go +++ b/internal/aghalg/nullbool_test.go @@ -10,6 +10,52 @@ import ( "github.com/stretchr/testify/require" ) +func TestNullBool_MarshalJSON(t *testing.T) { + testCases := []struct { + name string + wantErrMsg string + want []byte + in aghalg.NullBool + }{{ + name: "null", + wantErrMsg: "", + want: []byte("null"), + in: aghalg.NBNull, + }, { + name: "true", + wantErrMsg: "", + want: []byte("true"), + in: aghalg.NBTrue, + }, { + name: "false", + wantErrMsg: "", + want: []byte("false"), + in: aghalg.NBFalse, + }} + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + got, err := tc.in.MarshalJSON() + testutil.AssertErrorMsg(t, tc.wantErrMsg, err) + + assert.Equal(t, tc.want, got) + }) + } + + t.Run("json", func(t *testing.T) { + in := &struct { + A aghalg.NullBool + }{ + A: aghalg.NBTrue, + } + + got, err := json.Marshal(in) + require.NoError(t, err) + + assert.Equal(t, []byte(`{"A":true}`), got) + }) +} + func TestNullBool_UnmarshalJSON(t *testing.T) { testCases := []struct { name string