-
Notifications
You must be signed in to change notification settings - Fork 0
/
email_test.go
102 lines (88 loc) · 2.47 KB
/
email_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
package types_test
import (
"errors"
"reflect"
"testing"
"github.com/go-api-libs/types"
"github.com/go-json-experiment/json"
"github.com/go-json-experiment/json/jsontext"
)
type wrapEmail struct {
Email types.Email `json:"email,omitempty"`
}
type wrapPointerToEmail struct {
Email *types.Email `json:"email,omitempty"`
}
func TestEmail(t *testing.T) {
for _, tc := range []struct {
name string
json string
want string
}{
{"empty", `{"email":""}`, ""},
{"fully empty", `{}`, ""},
{"valid", `{"email":"[email protected]"}`, "[email protected]"},
} {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
t.Run("no pointer", func(t *testing.T) {
res := &wrapEmail{}
if err := json.Unmarshal([]byte(tc.json), res); err != nil {
t.Fatal(err)
}
if res.Email != types.Email(tc.want) {
t.Fatalf("got: %v, want: %v", res.Email, tc.want)
}
if tc.want != "" {
if err := res.Email.Validate(); err != nil {
t.Fatal(err)
}
}
})
t.Run("pointer", func(t *testing.T) {
res := &wrapPointerToEmail{}
if err := json.Unmarshal([]byte(tc.json), res); err != nil {
t.Fatal(err)
}
if (res.Email == nil && tc.want != "") ||
(res.Email != nil && *res.Email != types.Email(tc.want)) {
t.Fatalf("got: %#v, want: %q", res.Email, tc.want)
}
if tc.want != "" {
if err := res.Email.Validate(); err != nil {
t.Fatal(err, res.Email == nil)
}
}
})
})
}
}
func TestEmail_Errors(t *testing.T) {
emailType := reflect.TypeFor[types.Email]()
t.Run("invalid email", func(t *testing.T) {
body := []byte(`{"email":"foo"}`)
for _, out := range []any{&wrapEmail{}, &wrapPointerToEmail{}} {
semErr := &json.SemanticError{}
if err := json.Unmarshal(body, out); err == nil {
t.Fatal("expected error")
} else if !errors.As(err, &semErr) {
t.Fatalf("wanted: %T, got: %T", semErr, err)
} else if semErr.GoType != emailType {
t.Fatalf("wanted: %T, got: %T", emailType, semErr.GoType)
}
}
})
t.Run("unexpected EOF", func(t *testing.T) {
body := []byte(`{"email":"foo`)
for _, out := range []any{&wrapEmail{}, &wrapPointerToEmail{}} {
synErr := &jsontext.SyntacticError{}
if err := json.Unmarshal(body, out); err == nil {
t.Fatal("expected error")
} else if !errors.As(err, &synErr) {
t.Fatalf("wanted: %T, got: %T", synErr, err)
} else if want := `unexpected EOF`; synErr.Err.Error() != want {
t.Fatalf("wanted: %s, got: %s", want, synErr.Err)
}
}
})
}