...
1 package graphql
2
3 import (
4 "encoding/json"
5 "testing"
6
7 "github.com/stretchr/testify/assert"
8 "github.com/stretchr/testify/require"
9 )
10
11 func TestOmittable_MarshalJSON(t *testing.T) {
12 s := "test"
13 testCases := []struct {
14 name string
15 input any
16 expectedJSON string
17 }{
18 {
19 name: "simple string",
20 input: struct{ Value Omittable[string] }{Value: OmittableOf("simple string")},
21 expectedJSON: `{"Value": "simple string"}`,
22 },
23 {
24 name: "string pointer",
25 input: struct{ Value Omittable[*string] }{Value: OmittableOf(&s)},
26 expectedJSON: `{"Value": "test"}`,
27 },
28 {
29 name: "omitted integer",
30 input: struct{ Value Omittable[int] }{},
31 expectedJSON: `{"Value": null}`,
32 },
33 {
34 name: "omittable omittable",
35 input: struct{ Value Omittable[Omittable[uint64]] }{Value: OmittableOf(OmittableOf(uint64(42)))},
36 expectedJSON: `{"Value": 42}`,
37 },
38 {
39 name: "omittable struct",
40 input: struct {
41 Value Omittable[struct{ Inner string }]
42 }{Value: OmittableOf(struct{ Inner string }{})},
43 expectedJSON: `{"Value": {"Inner": ""}}`,
44 },
45 {
46 name: "omitted struct",
47 input: struct {
48 Value Omittable[struct{ Inner string }]
49 }{},
50 expectedJSON: `{"Value": null}`,
51 },
52 }
53
54 for _, tc := range testCases {
55 t.Run(tc.name, func(t *testing.T) {
56 data, err := json.Marshal(tc.input)
57 require.NoError(t, err)
58 assert.JSONEq(t, tc.expectedJSON, string(data))
59 })
60 }
61 }
62
63 func TestOmittable_UnmarshalJSON(t *testing.T) {
64 var s struct {
65 String Omittable[string]
66 OmittedString Omittable[string]
67 StringPointer Omittable[*string]
68 NullInt Omittable[int]
69 }
70
71 err := json.Unmarshal([]byte(`
72 {
73 "String": "simple string",
74 "StringPointer": "string pointer",
75 "NullInt": null
76 }`), &s)
77
78 require.NoError(t, err)
79 assert.Equal(t, "simple string", s.String.Value())
80 assert.True(t, s.String.IsSet())
81 assert.False(t, s.OmittedString.IsSet())
82 assert.True(t, s.StringPointer.IsSet())
83 if assert.NotNil(t, s.StringPointer.Value()) {
84 assert.EqualValues(t, "string pointer", *s.StringPointer.Value())
85 }
86 assert.True(t, s.NullInt.IsSet())
87 assert.Zero(t, s.NullInt.Value())
88 }
89
View as plain text