-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnullable_test.go
More file actions
86 lines (73 loc) · 2.41 KB
/
nullable_test.go
File metadata and controls
86 lines (73 loc) · 2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package main
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
)
type Obj struct {
Foo Nullable[string] `json:"foo,omitempty"` // note "omitempty" is important for fields that are optional
}
func TestNullable(t *testing.T) {
// --- parsing from json and serializing back to JSON
// -- case where there is an actual value
data := `{"foo":"bar"}`
// deserialize from json
myObj := parse(data, t)
require.Equal(t, myObj, Obj{Foo: Nullable[string]{true: "bar"}})
require.False(t, myObj.Foo.IsNull())
require.True(t, myObj.Foo.IsSpecified())
value, err := myObj.Foo.Get()
require.NoError(t, err)
require.Equal(t, "bar", value)
// serialize back to json: leads to the same data
require.Equal(t, data, serialize(myObj, t))
// -- case where no value is specified: parsed from JSON
data = `{}`
// deserialize from json
myObj = parse(data, t)
require.Equal(t, myObj, Obj{Foo: nil})
require.False(t, myObj.Foo.IsNull())
require.False(t, myObj.Foo.IsSpecified())
_, err = myObj.Foo.Get()
require.ErrorContains(t, err, "value is not specified")
// serialize back to json: leads to the same data
require.Equal(t, data, serialize(myObj, t))
// -- case where the specified value is explicitly null
data = `{"foo":null}`
// deserialize from json
myObj = parse(data, t)
require.Equal(t, myObj, Obj{Foo: Nullable[string]{false: ""}})
require.True(t, myObj.Foo.IsNull())
require.True(t, myObj.Foo.IsSpecified())
_, err = myObj.Foo.Get()
require.ErrorContains(t, err, "value is null")
// serialize back to json: leads to the same data
require.Equal(t, data, serialize(myObj, t))
// --- building objects from a Go client
// - case where there is an actual value
myObj = Obj{}
myObj.Foo.Set("bar")
require.Equal(t, `{"foo":"bar"}`, serialize(myObj, t))
// - case where the value should be unspecified
myObj = Obj{}
// do nothing: unspecified by default
require.Equal(t, `{}`, serialize(myObj, t))
// explicitly mark unspecified
myObj.Foo.SetUnspecified()
require.Equal(t, `{}`, serialize(myObj, t))
// - case where the value should be null
myObj = Obj{}
myObj.Foo.SetNull()
require.Equal(t, `{"foo":null}`, serialize(myObj, t))
}
func parse(data string, t *testing.T) Obj {
var myObj Obj
err := json.Unmarshal([]byte(data), &myObj)
require.NoError(t, err)
return myObj
}
func serialize(o Obj, t *testing.T) string {
data, err := json.Marshal(o)
require.NoError(t, err)
return string(data)
}