-
Notifications
You must be signed in to change notification settings - Fork 0
/
globalerrors_test.go
80 lines (68 loc) · 1.77 KB
/
globalerrors_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
package globalerrors
import (
"errors"
"google.golang.org/grpc/codes"
"net/http"
"testing"
)
func TestHTTPStatus(t *testing.T) {
tests := []struct {
name string
err error
want int
}{
{"BadRequest", BadRequest, http.StatusBadRequest},
{"Unauthorized", Unauthorized, http.StatusUnauthorized},
// Add all the other HTTP status error cases here
{"Unknown", errors.New("unknown"), http.StatusInternalServerError},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := HTTPStatus(tt.err)
if got != tt.want {
t.Errorf("HTTPStatus() = %v, want %v", got, tt.want)
}
})
}
}
func TestGRPCStatus(t *testing.T) {
tests := []struct {
name string
err error
want codes.Code
}{
{"BadRequest", BadRequest, codes.InvalidArgument},
{"Unauthorized", Unauthorized, codes.Unauthenticated},
// Add all the other gRPC status error cases here
{"Unknown", errors.New("unknown"), codes.Internal},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := GRPCStatus(tt.err)
if got != tt.want {
t.Errorf("GRPCStatus() = %v, want %v", got, tt.want)
}
})
}
}
func TestCustomErrorCompatibility(t *testing.T) {
err := ErrIDIsRequired()
httpStatus := HTTPStatus(err)
grpcStatus := GRPCStatus(err)
if httpStatus != http.StatusUnprocessableEntity {
t.Errorf("Expected HTTPStatus to be 422, got %d", httpStatus)
}
if grpcStatus != codes.InvalidArgument {
t.Errorf("Expected GRPCStatus to be InvalidArgument, got %s", grpcStatus.String())
}
}
func ErrIDIsRequired() error {
return errIDIsRequired{}
}
type errIDIsRequired struct{}
func (e errIDIsRequired) Error() string {
return "id is required"
}
func (e errIDIsRequired) Is(target error) bool {
return errors.Is(target, UnprocessableEntity) || e == target
}