-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrors_test.go
More file actions
97 lines (73 loc) · 2.38 KB
/
Copy patherrors_test.go
File metadata and controls
97 lines (73 loc) · 2.38 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
package apihandler_test
import (
"errors"
"fmt"
"net/http"
"testing"
apihandler "github.com/wickedbyte/api-handler-go"
)
// errCause is the sentinel wrapped cause used by the StatusError tests.
var errCause = errors.New("connection refused")
// detailUpstreamUnavailable is the client-safe detail shared by the
// StatusError and writer-logging tests.
const detailUpstreamUnavailable = "upstream unavailable"
func TestStatusErrorMessageWithoutCause(t *testing.T) {
t.Parallel()
err := apihandler.Error(http.StatusNotFound, "no such user")
if got, want := err.Error(), "404 no such user"; got != want {
t.Fatalf("message = %q, want %q", got, want)
}
}
func TestStatusErrorMessageWithCause(t *testing.T) {
t.Parallel()
err := &apihandler.StatusError{
Status: http.StatusBadGateway,
Detail: detailUpstreamUnavailable,
Err: errCause,
}
if got, want := err.Error(), "502 upstream unavailable: connection refused"; got != want {
t.Fatalf("message = %q, want %q", got, want)
}
}
func TestStatusErrorUnwrapExposesCause(t *testing.T) {
t.Parallel()
err := &apihandler.StatusError{
Status: http.StatusBadGateway,
Detail: detailUpstreamUnavailable,
Err: errCause,
}
if !errors.Is(err, errCause) {
t.Fatal("errors.Is did not find the wrapped cause")
}
if !errors.Is(errors.Unwrap(err), errCause) {
t.Fatal("Unwrap did not return the wrapped cause")
}
}
func TestErrorConstructsStatusError(t *testing.T) {
t.Parallel()
err := apihandler.Error(http.StatusConflict, "already exists")
if err.Status != http.StatusConflict || err.Detail != "already exists" {
t.Fatalf("err = %+v", err)
}
if err.HTTPStatus() != http.StatusConflict {
t.Fatalf("HTTPStatus() = %d", err.HTTPStatus())
}
var statusErr *apihandler.StatusError
if !errors.As(err, &statusErr) {
t.Fatalf("err = %T, want *apihandler.StatusError", err)
}
if statusErr.Status != http.StatusConflict || statusErr.Detail != "already exists" {
t.Fatalf("statusErr = %+v", statusErr)
}
}
func TestErrorsAsFindsHTTPStatusThroughWrapping(t *testing.T) {
t.Parallel()
wrapped := fmt.Errorf("loading user: %w", apihandler.Error(http.StatusNotFound, "no such user"))
var carrier interface{ HTTPStatus() int }
if !errors.As(wrapped, &carrier) {
t.Fatal("errors.As did not find the HTTPStatus carrier")
}
if carrier.HTTPStatus() != http.StatusNotFound {
t.Fatalf("HTTPStatus() = %d", carrier.HTTPStatus())
}
}