-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem_test.go
More file actions
203 lines (175 loc) · 5.76 KB
/
problem_test.go
File metadata and controls
203 lines (175 loc) · 5.76 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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
package problem_test
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"github.com/semmidev/problem"
)
func TestProblemSerialization(t *testing.T) {
t.Run("marshaling", func(t *testing.T) {
p := problem.New(
problem.BadRequest,
problem.WithDetail("Invalid input provided"),
problem.WithInstance("/api/v1/users"),
problem.WithExtension("trace_id", "req-1234"),
problem.WithExtension("balance", 5000),
)
data, err := json.Marshal(p)
if err != nil {
t.Fatalf("failed to marshal: %v", err)
}
var raw map[string]any
if err := json.Unmarshal(data, &raw); err != nil {
t.Fatalf("failed to unmarshal back to map: %v", err)
}
// Ensure top-level fields match expectations
if raw["type"] != "about:blank" {
t.Errorf("expected type 'about:blank', got %v", raw["type"])
}
if raw["title"] != "Bad Request" {
t.Errorf("expected title 'Bad Request', got %v", raw["title"])
}
if raw["status"].(float64) != float64(http.StatusBadRequest) {
t.Errorf("expected status %v, got %v", http.StatusBadRequest, raw["status"])
}
if raw["detail"] != "Invalid input provided" {
t.Errorf("expected detail, got %v", raw["detail"])
}
if raw["instance"] != "/api/v1/users" {
t.Errorf("expected instance, got %v", raw["instance"])
}
if raw["trace_id"] != "req-1234" {
t.Errorf("expected trace_id extension, got %v", raw["trace_id"])
}
if raw["balance"].(float64) != 5000 {
t.Errorf("expected balance extension, got %v", raw["balance"])
}
})
t.Run("unmarshaling", func(t *testing.T) {
rawJSON := []byte(`{
"type": "https://example.com/probs/out-of-credit",
"title": "You do not have enough credit.",
"status": 403,
"detail": "Your current balance is 30, but that costs 50.",
"instance": "/account/12345/msgs/abc",
"balance": 30,
"accounts": ["/account/12345", "/account/67890"]
}`)
var p problem.Problem
if err := json.Unmarshal(rawJSON, &p); err != nil {
t.Fatalf("failed to unmarshal: %v", err)
}
if p.Type != "https://example.com/probs/out-of-credit" {
t.Errorf("bad type: %s", p.Type)
}
if p.Title != "You do not have enough credit." {
t.Errorf("bad title: %s", p.Title)
}
if p.Status != 403 {
t.Errorf("bad status: %d", p.Status)
}
if p.Detail != "Your current balance is 30, but that costs 50." {
t.Errorf("bad detail: %s", p.Detail)
}
if p.Instance != "/account/12345/msgs/abc" {
t.Errorf("bad instance: %s", p.Instance)
}
// Extensions
if p.Extensions == nil {
t.Fatal("expected extensions to be initialized")
}
if p.Extensions["balance"].(float64) != 30 {
t.Errorf("bad extension balance: %v", p.Extensions["balance"])
}
// check accounts list length
accounts, ok := p.Extensions["accounts"].([]any)
if !ok || len(accounts) != 2 {
t.Errorf("bad extension accounts array: %v", p.Extensions["accounts"])
}
})
}
func TestProblemErrorWrapping(t *testing.T) {
origErr := errors.New("underlying generic network timeout")
p := problem.Wrap(origErr, problem.GatewayTimeout, problem.WithDetail("Upstream service failed"))
// Implement Standard Error()
if p.Error() == "" {
t.Error("error string should not be empty")
}
// Unwrap
if unwrapped := p.Unwrap(); unwrapped != origErr {
t.Errorf("expected to unwrap origErr, got: %v", unwrapped)
}
// errors.Is check
if !errors.Is(p, origErr) {
t.Error("errors.Is should return true for underlying error")
}
// errors.As check (getting Problem back out of an error)
var asErr *problem.Problem
if !errors.As(p, &asErr) {
t.Error("errors.As should extract Problem from itself")
}
// Double-wrapping scenario (simulating fmt.Errorf)
wrap2 := fmt.Errorf("adding more context: %w", p)
if !errors.As(wrap2, &asErr) {
t.Error("errors.As should extract Problem from a wrapped generic error")
}
// IsProblem convenience
if extracted, ok := problem.IsProblem(wrap2); !ok || extracted == nil {
t.Error("IsProblem should successfully extract the Problem from a wrapped error")
}
}
func TestProblemHTTPWrite(t *testing.T) {
p := problem.New(problem.InternalServerError, problem.WithDetail("DB connection failed"))
rec := httptest.NewRecorder()
if err := p.Write(rec); err != nil {
t.Fatalf("Write should not return error: %v", err)
}
res := rec.Result()
if res.StatusCode != 500 {
t.Errorf("bad status code, expected 500 got %d", res.StatusCode)
}
contentType := res.Header.Get("Content-Type")
if contentType != "application/problem+json; charset=utf-8" {
t.Errorf("bad content type: %s", contentType)
}
if snif := res.Header.Get("X-Content-Type-Options"); snif != "nosniff" {
t.Errorf("expected nosniff, got %v", snif)
}
}
func TestProblemHTTPHelpers(t *testing.T) {
p := problem.New(problem.BadRequest, problem.WithDetail("Invalid ID"))
t.Run("Headers", func(t *testing.T) {
headers := p.Headers()
if headers["Content-Type"] != problem.ContentType {
t.Errorf("expected Content-Type %s, got %s", problem.ContentType, headers["Content-Type"])
}
if headers["X-Content-Type-Options"] != "nosniff" {
t.Errorf("expected X-Content-Type-Options nosniff, got %s", headers["X-Content-Type-Options"])
}
})
t.Run("JSON", func(t *testing.T) {
data := p.JSON()
var m map[string]any
if err := json.Unmarshal(data, &m); err != nil {
t.Fatalf("JSON() returned invalid json: %v", err)
}
if m["title"] != "Bad Request" || m["detail"] != "Invalid ID" {
t.Errorf("JSON() content mismatch: %v", m)
}
})
t.Run("Map", func(t *testing.T) {
m := p.Map()
if m["title"] != "Bad Request" {
t.Errorf("Map() expected title 'Bad Request', got %v", m["title"])
}
if m["status"].(float64) != 400 {
t.Errorf("Map() expected status 400, got %v", m["status"])
}
if m["detail"] != "Invalid ID" {
t.Errorf("Map() expected detail 'Invalid ID', got %v", m["detail"])
}
})
}