-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrors_test.go
More file actions
111 lines (102 loc) · 2.61 KB
/
errors_test.go
File metadata and controls
111 lines (102 loc) · 2.61 KB
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
package hostlib
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestErrorResponse_ToJSON(t *testing.T) {
tests := []struct {
name string
err ErrorResponse
expected string
}{
{
name: "validation error",
err: ErrorResponse{
Error: "VALIDATION_ERROR",
Message: "invalid JSON",
Code: 400,
},
expected: `{"error":"VALIDATION_ERROR","message":"invalid JSON","code":400}`,
},
{
name: ErrorResponse{
Error: "NOT_FOUND",
Message: "unknown host function: foo",
Code: 404,
}.Error,
err: ErrorResponse{
Error: "NOT_FOUND",
Message: "unknown host function: foo",
Code: 404,
},
expected: `{"error":"NOT_FOUND","message":"unknown host function: foo","code":404}`,
},
{
name: "internal error",
err: ErrorResponse{
Error: "INTERNAL_ERROR",
Message: "panic: oh no",
Code: 500,
},
expected: `{"error":"INTERNAL_ERROR","message":"panic: oh no","code":500}`,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := tt.err.ToJSON()
require.NotNil(t, got)
assert.JSONEq(t, tt.expected, string(got))
})
}
}
func TestNewValidationError(t *testing.T) {
err := NewValidationError("failed to unmarshal request")
assert.Equal(t, "VALIDATION_ERROR", err.Error)
assert.Equal(t, "failed to unmarshal request", err.Message)
assert.Equal(t, 400, err.Code)
}
func TestNewNotFoundError(t *testing.T) {
err := NewNotFoundError("unknown_func")
assert.Equal(t, "NOT_FOUND", err.Error)
assert.Equal(t, "unknown host function: unknown_func", err.Message)
assert.Equal(t, 404, err.Code)
}
func TestNewInternalError(t *testing.T) {
err := NewInternalError("database connection failed")
assert.Equal(t, "INTERNAL_ERROR", err.Error)
assert.Equal(t, "database connection failed", err.Message)
assert.Equal(t, 500, err.Code)
}
func TestNewPanicError(t *testing.T) {
tests := []struct {
name string
panicValue any
wantMsg string
}{
{
name: "string panic",
panicValue: "oops",
wantMsg: "panic: oops",
},
{
name: "error panic",
panicValue: func() error { var v any; return json.Unmarshal(nil, &v) }(),
wantMsg: "panic: unexpected end of JSON input",
},
{
name: "other panic",
panicValue: 42,
wantMsg: "panic: panic recovered",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := NewPanicError(tt.panicValue)
assert.Equal(t, "INTERNAL_ERROR", err.Error)
assert.Equal(t, tt.wantMsg, err.Message)
assert.Equal(t, 500, err.Code)
})
}
}