-
Notifications
You must be signed in to change notification settings - Fork 57
/
animal_test.go
124 lines (113 loc) · 2.71 KB
/
animal_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 animalData struct {
AnimalX Animal `json:"animal"`
}
func TestAnimalString(t *testing.T) {
x := Animal(109)
assert.Equal(t, "Animal(109)", x.String())
x = Animal(1)
assert.Equal(t, "Dog", x.String())
y, err := ParseAnimal("Cat")
require.NoError(t, err, "Failed parsing cat")
assert.Equal(t, AnimalCat, y)
z, err := ParseAnimal("Snake")
require.Error(t, err, "Shouldn't parse a snake")
assert.Equal(t, Animal(0), z)
}
func TestAnimalUnmarshal(t *testing.T) {
tests := []struct {
name string
input string
output *animalData
errorExpected bool
err error
}{
{
name: "cat",
input: `{"animal":0}`,
output: &animalData{AnimalX: AnimalCat},
errorExpected: false,
err: nil,
},
{
name: "dog",
input: `{"animal":1}`,
output: &animalData{AnimalX: AnimalDog},
errorExpected: false,
err: nil,
},
{
name: "fish",
input: `{"animal":2}`,
output: &animalData{AnimalX: AnimalFish},
errorExpected: false,
err: nil,
},
{
name: "notananimal",
input: `{"animal":22}`,
output: &animalData{AnimalX: Animal(22)},
errorExpected: false,
err: nil,
},
}
for _, test := range tests {
t.Run(test.name, func(tt *testing.T) {
x := &animalData{}
err := json.Unmarshal([]byte(test.input), x)
if !test.errorExpected {
require.NoError(tt, err, "failed unmarshalling the json.")
assert.Equal(tt, test.output.AnimalX, x.AnimalX)
} else {
require.Error(tt, err)
assert.EqualError(tt, err, test.err.Error())
}
})
}
}
func TestAnimalMarshal(t *testing.T) {
tests := []struct {
name string
input *animalData
output string
errorExpected bool
err error
}{
{
name: "cat",
output: `{"animal":0}`,
input: &animalData{AnimalX: AnimalCat},
errorExpected: false,
err: nil,
},
{
name: "dog",
output: `{"animal":1}`,
input: &animalData{AnimalX: AnimalDog},
errorExpected: false,
err: nil,
},
{
name: "fish",
output: `{"animal":2}`,
input: &animalData{AnimalX: AnimalFish},
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))
})
}
}