From 5f4d7154c0f2796156698ca1fdaf41276a32ebbf Mon Sep 17 00:00:00 2001 From: Nick Craig-Wood Date: Thu, 16 Mar 2023 18:20:23 +0000 Subject: [PATCH] fs: fix tristate conversion to JSON --- fs/tristate.go | 8 ++++++++ fs/tristate_test.go | 15 +++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/fs/tristate.go b/fs/tristate.go index d03926a07..dd70a6a62 100644 --- a/fs/tristate.go +++ b/fs/tristate.go @@ -70,3 +70,11 @@ func (t *Tristate) UnmarshalJSON(in []byte) error { } return nil } + +// MarshalJSON encodes it as a bool or nil for unset +func (t *Tristate) MarshalJSON() ([]byte, error) { + if !t.Valid { + return json.Marshal(nil) + } + return json.Marshal(t.Value) +} diff --git a/fs/tristate_test.go b/fs/tristate_test.go index 9189f2293..fe0822d4b 100644 --- a/fs/tristate_test.go +++ b/fs/tristate_test.go @@ -85,3 +85,18 @@ func TestTristateUnmarshalJSON(t *testing.T) { assert.Equal(t, test.want, got, test.in) } } + +func TestTristateMarshalJSON(t *testing.T) { + for _, test := range []struct { + in Tristate + want string + }{ + {Tristate{}, `null`}, + {Tristate{Valid: true, Value: true}, `true`}, + {Tristate{Valid: true, Value: false}, `false`}, + } { + got, err := json.Marshal(&test.in) + require.NoError(t, err) + assert.Equal(t, test.want, string(got), fmt.Sprintf("%#v", test.in)) + } +}