/
dataeq_test.go
134 lines (128 loc) · 2.27 KB
/
dataeq_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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package dataeq_test
import (
"fmt"
"testing"
"github.com/stretchr/testify/require"
"github.com/suzuki-shunsuke/go-dataeq/dataeq"
)
type (
invalidMarshaler struct{}
)
func (m *invalidMarshaler) MarshalJSON() ([]byte, error) {
return nil, fmt.Errorf("failed to marshal")
}
func TestJSON_Convert(t *testing.T) {
t.Parallel()
data := []struct {
title string
x interface{}
isError bool
exp interface{}
}{
{
title: "simple []byte map",
x: []byte(`{"foo": "bar"}`),
exp: map[string]interface{}{
"foo": "bar",
},
},
{
title: "simple array",
x: []string{"foo", "bar"},
exp: []interface{}{"foo", "bar"},
},
{
title: "simple int",
x: 5,
exp: float64(5),
},
{
title: "simple nil",
x: nil,
exp: nil,
},
{
title: "failed to marshal",
x: &invalidMarshaler{},
isError: true,
},
}
for _, d := range data {
d := d
t.Run(d.title, func(t *testing.T) {
t.Parallel()
var a interface{}
err := dataeq.JSON.Convert(d.x, &a)
if d.isError {
require.NotNil(t, err)
return
}
require.Nil(t, err)
require.Equal(t, d.exp, a)
})
}
}
func TestJSON_Equal(t *testing.T) { //nolint:funlen
t.Parallel()
data := []struct {
title string
x interface{}
y interface{}
isError bool
exp bool
}{
{
title: "compare equal map",
x: map[string]string{
"foo": "bar",
},
y: map[string]string{
"foo": "bar",
},
exp: true,
},
{
title: "compare []byte and map",
x: []byte(`{"foo": "bar"}`),
y: map[string]string{
"foo": "bar",
},
exp: true,
},
{
title: "compare empty map and nil",
x: nil,
y: map[string]string{},
exp: false,
},
{
title: "failed to marshal x",
x: &invalidMarshaler{},
y: map[string]string{},
isError: true,
},
{
title: "failed to marshal y",
x: map[string]string{},
y: &invalidMarshaler{},
isError: true,
},
}
for _, d := range data {
d := d
t.Run(d.title, func(t *testing.T) {
t.Parallel()
f, err := dataeq.JSON.Equal(d.x, d.y)
if d.isError {
require.NotNil(t, err)
return
}
require.Nil(t, err)
if d.exp {
require.True(t, f)
} else {
require.False(t, f)
}
})
}
}