-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodes_test.go
More file actions
396 lines (335 loc) · 10.4 KB
/
codes_test.go
File metadata and controls
396 lines (335 loc) · 10.4 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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
package result
import (
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"testing"
)
// ============================================================================
// HTTPStatus Tests
// ============================================================================
func TestHTTPStatus_AllKinds(t *testing.T) {
tests := []struct {
name string
err error
expected int
}{
{
name: "Domain error",
err: Domain("test", "business rule violated"),
expected: http.StatusUnprocessableEntity, // 422
},
{
name: "Validation error",
err: Validation("test", "invalid input", nil),
expected: http.StatusBadRequest, // 400
},
{
name: "NotFound error",
err: NotFound("test", "resource"),
expected: http.StatusNotFound, // 404
},
{
name: "Conflict error",
err: Conflict("test", "resource"),
expected: http.StatusConflict, // 409
},
{
name: "Unauthorized error",
err: Unauthorized("test", "invalid token"),
expected: http.StatusUnauthorized, // 401
},
{
name: "Forbidden error",
err: Forbidden("test", "insufficient permissions"),
expected: http.StatusForbidden, // 403
},
{
name: "Infrastructure error",
err: Infrastructure("test", errors.New("db down")),
expected: http.StatusServiceUnavailable, // 503
},
{
name: "Internal error",
err: Internal("test", errors.New("panic")),
expected: http.StatusInternalServerError, // 500
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
status := HTTPStatus(tt.err)
if status != tt.expected {
t.Errorf("HTTPStatus() = %d, want %d", status, tt.expected)
}
})
}
}
func TestHTTPStatus_NilError(t *testing.T) {
status := HTTPStatus(nil)
if status != http.StatusInternalServerError {
t.Errorf("HTTPStatus(nil) = %d, want %d", status, http.StatusInternalServerError)
}
}
func TestHTTPStatus_StandardError(t *testing.T) {
// Standard Go error (not result.Error)
err := errors.New("standard error")
status := HTTPStatus(err)
// Should default to Internal (500)
if status != http.StatusInternalServerError {
t.Errorf("HTTPStatus(standard error) = %d, want %d", status, http.StatusInternalServerError)
}
}
// ============================================================================
// HTTPStatusResult Tests
// ============================================================================
func TestHTTPStatusResult_Ok(t *testing.T) {
r := Ok(42)
status := HTTPStatusResult(r)
if status != http.StatusOK {
t.Errorf("HTTPStatusResult(Ok) = %d, want %d", status, http.StatusOK)
}
}
func TestHTTPStatusResult_Err(t *testing.T) {
tests := []struct {
name string
result Result[int]
expected int
}{
{
name: "NotFound",
result: Err[int](NotFound("test", "resource")),
expected: http.StatusNotFound,
},
{
name: "Validation",
result: Err[int](Validation("test", "invalid", nil)),
expected: http.StatusBadRequest,
},
{
name: "Internal",
result: Err[int](Internal("test", errors.New("error"))),
expected: http.StatusInternalServerError,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
status := HTTPStatusResult(tt.result)
if status != tt.expected {
t.Errorf("HTTPStatusResult() = %d, want %d", status, tt.expected)
}
})
}
}
// ============================================================================
// HTTPStatusOr Tests
// ============================================================================
func TestHTTPStatusOr_Ok(t *testing.T) {
tests := []struct {
name string
result Result[int]
successStatus int
expected int
}{
{
name: "Ok with 200",
result: Ok(42),
successStatus: http.StatusOK,
expected: http.StatusOK,
},
{
name: "Ok with 201 Created",
result: Ok(42),
successStatus: http.StatusCreated,
expected: http.StatusCreated,
},
{
name: "Ok with 204 No Content",
result: Ok(42),
successStatus: http.StatusNoContent,
expected: http.StatusNoContent,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
status := HTTPStatusOr(tt.result, tt.successStatus)
if status != tt.expected {
t.Errorf("HTTPStatusOr() = %d, want %d", status, tt.expected)
}
})
}
}
func TestHTTPStatusOr_Err(t *testing.T) {
r := Err[int](NotFound("test", "resource"))
status := HTTPStatusOr(r, http.StatusCreated)
// Should return error status, not success status
if status != http.StatusNotFound {
t.Errorf("HTTPStatusOr(Err) = %d, want %d", status, http.StatusNotFound)
}
}
// ============================================================================
// WriteHTTPError Tests
// ============================================================================
func TestWriteHTTPError_WithoutMetadata(t *testing.T) {
err := NotFound("test", "resource")
w := httptest.NewRecorder()
WriteHTTPError(w, err)
if w.Code != http.StatusNotFound {
t.Errorf("status code = %d, want %d", w.Code, http.StatusNotFound)
}
// Should be plain text (no JSON)
contentType := w.Header().Get("Content-Type")
if contentType == "application/json" {
t.Error("Should not set JSON content type for errors without metadata")
}
body := w.Body.String()
if body == "" {
t.Error("Body should not be empty")
}
}
func TestWriteHTTPError_WithMetadata(t *testing.T) {
err := Validation("test", "invalid email", map[string]interface{}{
"field": "email",
"value": "invalid",
})
w := httptest.NewRecorder()
WriteHTTPError(w, err)
if w.Code != http.StatusBadRequest {
t.Errorf("status code = %d, want %d", w.Code, http.StatusBadRequest)
}
// Should be JSON
contentType := w.Header().Get("Content-Type")
if contentType != "application/json" {
t.Errorf("content type = %s, want application/json", contentType)
}
// Parse JSON response
var response map[string]interface{}
if err := json.NewDecoder(w.Body).Decode(&response); err != nil {
t.Fatalf("Failed to decode JSON response: %v", err)
}
// Check response structure
if response["error"] == nil {
t.Error("Response should have 'error' field")
}
if response["kind"] != "validation" {
t.Errorf("Response kind = %v, want validation", response["kind"])
}
if response["op"] != "test" {
t.Errorf("Response op = %v, want test", response["op"])
}
details, ok := response["details"].(map[string]interface{})
if !ok {
t.Fatal("Response should have 'details' map")
}
if details["field"] != "email" {
t.Errorf("details[field] = %v, want email", details["field"])
}
}
func TestWriteHTTPError_NilMetadata(t *testing.T) {
err := Domain("test", "business rule violated")
w := httptest.NewRecorder()
WriteHTTPError(w, err)
if w.Code != http.StatusUnprocessableEntity {
t.Errorf("status code = %d, want %d", w.Code, http.StatusUnprocessableEntity)
}
// Should be plain text (no metadata)
contentType := w.Header().Get("Content-Type")
if contentType == "application/json" {
t.Error("Should not set JSON content type for errors without metadata")
}
}
func TestWriteHTTPError_EmptyMetadata(t *testing.T) {
err := Validation("test", "invalid", map[string]interface{}{})
w := httptest.NewRecorder()
WriteHTTPError(w, err)
// Empty metadata is still metadata, should return JSON
contentType := w.Header().Get("Content-Type")
if contentType != "application/json" {
t.Errorf("content type = %s, want application/json", contentType)
}
}
func TestWriteHTTPError_AllErrorKinds(t *testing.T) {
tests := []struct {
name string
err error
expectedCode int
}{
{"Domain", Domain("test", "msg"), http.StatusUnprocessableEntity},
{"Validation", Validation("test", "msg", nil), http.StatusBadRequest},
{"NotFound", NotFound("test", "resource"), http.StatusNotFound},
{"Conflict", Conflict("test", "resource"), http.StatusConflict},
{"Unauthorized", Unauthorized("test", "msg"), http.StatusUnauthorized},
{"Forbidden", Forbidden("test", "msg"), http.StatusForbidden},
{"Infrastructure", Infrastructure("test", errors.New("db")), http.StatusServiceUnavailable},
{"Internal", Internal("test", errors.New("panic")), http.StatusInternalServerError},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
w := httptest.NewRecorder()
WriteHTTPError(w, tt.err)
if w.Code != tt.expectedCode {
t.Errorf("status code = %d, want %d", w.Code, tt.expectedCode)
}
})
}
}
// ============================================================================
// Integration Tests
// ============================================================================
func TestHTTPStatus_WithWrappedError(t *testing.T) {
original := NotFound("repo", "user")
wrapped := Wrap(original, "service")
status := HTTPStatus(wrapped)
// Should preserve NotFound kind
if status != http.StatusNotFound {
t.Errorf("HTTPStatus(wrapped) = %d, want %d", status, http.StatusNotFound)
}
}
func TestWriteHTTPError_RealWorldResponse(t *testing.T) {
// Simulate a validation error with rich metadata
err := Validation("UserService.CreateUser", "invalid email format", map[string]interface{}{
"field": "email",
"value": "invalid@",
"constraint": "email",
"request_id": "req_123",
})
w := httptest.NewRecorder()
WriteHTTPError(w, err)
// Should be 400
if w.Code != http.StatusBadRequest {
t.Errorf("status = %d, want 400", w.Code)
}
// Should be JSON
var response map[string]interface{}
json.NewDecoder(w.Body).Decode(&response)
// Verify structure
if response["error"] == nil {
t.Error("Missing error field")
}
if response["kind"] != "validation" {
t.Error("Wrong kind")
}
if response["op"] != "UserService.CreateUser" {
t.Error("Wrong op")
}
details := response["details"].(map[string]interface{})
if details["field"] != "email" || details["request_id"] != "req_123" {
t.Error("Missing or wrong metadata")
}
}
func TestHTTPStatusOr_CreateEndpoint(t *testing.T) {
// Simulate create operation
createResult := Ok(&struct{ ID string }{ID: "user_123"})
status := HTTPStatusOr(createResult, http.StatusCreated)
if status != http.StatusCreated {
t.Errorf("Create success should return 201, got %d", status)
}
}
func TestHTTPStatusOr_DeleteEndpoint(t *testing.T) {
// Simulate delete operation
deleteResult := Ok(struct{}{})
status := HTTPStatusOr(deleteResult, http.StatusNoContent)
if status != http.StatusNoContent {
t.Errorf("Delete success should return 204, got %d", status)
}
}