-
Notifications
You must be signed in to change notification settings - Fork 0
/
problem_test.go
98 lines (76 loc) · 2.43 KB
/
problem_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
package akumu_test
import (
"encoding/json"
"net/http"
"testing"
"github.com/studiolambda/akumu"
)
var (
ErrNotAuthenticated = akumu.Problem{
Type: "http://example.com/problems/unauthenticated",
Title: "Unauthenticated",
Detail: "The supplied credentials are invalid",
Status: http.StatusUnauthorized,
}
)
func customProblemHandler(request *http.Request) error {
return akumu.Failed(
ErrNotAuthenticated.With("username", "foobar"),
)
}
func customProblemHandler2(request *http.Request) error {
return akumu.
Failed(ErrNotAuthenticated).
Header("X-Foo", "Bar")
}
func problemHandler(request *http.Request) error {
return akumu.Failed(akumu.Problem{
Type: "http://example.com/problems/not-found",
Title: http.StatusText(http.StatusNotFound),
Detail: "The requested resource could not be found.",
Status: http.StatusNotFound,
Instance: request.URL.String(),
})
}
func TestItHandlesErrorsWithHeaders(t *testing.T) {
request, err := http.NewRequest("GET", "/", nil)
request.Header.Add("Accept", "application/problem+json")
if err != nil {
t.Fatalf("unable to create request: %s", err)
}
response := akumu.Record(customProblemHandler2, request)
if response.Code != ErrNotAuthenticated.Status {
t.Fatalf("unexpected status code: %d, expected %d", response.Code, ErrNotAuthenticated.Status)
}
if value := response.Header().Get("X-Foo"); value != "Bar" {
t.Fatalf("unexpected header value: %s, expected %s", value, "Bar")
}
}
func TestProblemHandler(t *testing.T) {
request, err := http.NewRequest("GET", "/", nil)
if err != nil {
t.Fatalf("unable to create request: %s", err)
}
response := akumu.Record(problemHandler, request)
if response.Code != http.StatusNotFound {
t.Fatalf("unexpected status code: %d", response.Code)
}
}
func TestCustomProblemHandler(t *testing.T) {
request, err := http.NewRequest("GET", "/", nil)
request.Header.Add("Accept", "application/problem+json")
if err != nil {
t.Fatalf("unable to create request: %s", err)
}
response := akumu.Record(customProblemHandler, request)
data := make(map[string]any)
if err := json.Unmarshal(response.Body.Bytes(), &data); err != nil {
t.Fatalf("unable to deserialize response body: %s", err)
}
if response.Code != http.StatusUnauthorized {
t.Fatalf("unexpected status code: %d", response.Code)
}
if username, ok := data["username"]; !ok || username != "foobar" {
t.Fatalf("unexpected username: %s", username)
}
}