-
Notifications
You must be signed in to change notification settings - Fork 57
/
custom_prefix_test.go
124 lines (113 loc) · 2.85 KB
/
custom_prefix_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
//go:build example
// +build example
package example
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type productData struct {
ProductX Product `json:"product"`
}
func TestProductString(t *testing.T) {
x := Product(109)
assert.Equal(t, "Product(109)", x.String())
x = Product(1)
assert.Equal(t, "Dynamite", x.String())
y, err := ParseProduct("Anvil")
require.NoError(t, err, "Failed parsing anvil")
assert.Equal(t, AcmeIncProductAnvil, y)
z, err := ParseProduct("Snake")
require.Error(t, err, "Shouldn't parse a snake")
assert.Equal(t, Product(0), z)
}
func TestProductUnmarshal(t *testing.T) {
tests := []struct {
name string
input string
output *productData
errorExpected bool
err error
}{
{
name: "anvil",
input: `{"product":0}`,
output: &productData{ProductX: AcmeIncProductAnvil},
errorExpected: false,
err: nil,
},
{
name: "dynamite",
input: `{"product":1}`,
output: &productData{ProductX: AcmeIncProductDynamite},
errorExpected: false,
err: nil,
},
{
name: "glue",
input: `{"product":2}`,
output: &productData{ProductX: AcmeIncProductGlue},
errorExpected: false,
err: nil,
},
{
name: "notanproduct",
input: `{"product":22}`,
output: &productData{ProductX: Product(22)},
errorExpected: false,
err: nil,
},
}
for _, test := range tests {
t.Run(test.name, func(tt *testing.T) {
x := &productData{}
err := json.Unmarshal([]byte(test.input), x)
if !test.errorExpected {
require.NoError(tt, err, "failed unmarshalling the json.")
assert.Equal(tt, test.output.ProductX, x.ProductX)
} else {
require.Error(tt, err)
assert.EqualError(tt, err, test.err.Error())
}
})
}
}
func TestProductMarshal(t *testing.T) {
tests := []struct {
name string
input *productData
output string
errorExpected bool
err error
}{
{
name: "anvil",
output: `{"product":0}`,
input: &productData{ProductX: AcmeIncProductAnvil},
errorExpected: false,
err: nil,
},
{
name: "dynamite",
output: `{"product":1}`,
input: &productData{ProductX: AcmeIncProductDynamite},
errorExpected: false,
err: nil,
},
{
name: "glue",
output: `{"product":2}`,
input: &productData{ProductX: AcmeIncProductGlue},
errorExpected: false,
err: nil,
},
}
for _, test := range tests {
t.Run(test.name, func(tt *testing.T) {
raw, err := json.Marshal(test.input)
require.NoError(tt, err, "failed marshalling to json")
assert.JSONEq(tt, test.output, string(raw))
})
}
}