-
Notifications
You must be signed in to change notification settings - Fork 0
/
string_test.go
106 lines (96 loc) · 1.98 KB
/
string_test.go
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/*
Copyright © Portalnesia <support@portalnesia.com>
*/
package nullable
import (
"bytes"
"testing"
"encoding/json"
)
type stringJsonTest struct {
Value String `json:"value,omitempty"`
}
func TestString_MarshalJSON(t *testing.T) {
tests := []struct {
name string
data stringJsonTest
expect *bytes.Buffer
}{
{
name: "null value",
data: stringJsonTest{
Value: String{
Present: true,
Valid: false,
},
},
expect: bytes.NewBufferString(`{"value":null}`),
},
{
name: "valid value",
data: stringJsonTest{
Value: String{
Present: true,
Valid: true,
Data: "test",
},
},
expect: bytes.NewBufferString(`{"value":"test"}`),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var byt []byte
var err error
if byt, err = json.Marshal(tt.data); err != nil {
t.Fatalf("unexpected marshaling error: %s", err)
}
if !bytes.Equal(byt, tt.expect.Bytes()) {
t.Errorf("expected value to be %s got %s", tt.expect, byt)
}
})
}
}
func TestString_UnmarshalJSON(t *testing.T) {
tests := []struct {
name string
buf *bytes.Buffer
expect String
}{
{
name: "null value",
buf: bytes.NewBufferString(`{"value":null}`),
expect: String{
Present: true,
},
},
{
name: "valid value",
buf: bytes.NewBufferString(`{"value":"string"}`),
expect: String{
Present: true,
Valid: true,
Data: "string",
},
},
{
name: "empty",
buf: bytes.NewBufferString(`null`),
expect: String{},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
str := struct {
Value String `json:"value"`
}{}
if err := json.Unmarshal(tt.buf.Bytes(), &str); err != nil {
t.Fatalf("unexpected unmarshaling error: %s", err)
}
got := str.Value
if got.Present != tt.expect.Present || got.Valid != tt.expect.Valid || got.Data != tt.expect.Data {
t.Errorf("expected value to be %#v got %#v", tt.expect, got)
}
})
}
}