Repository navigation
Expand file tree
/
Copy patherrors_auth_test.go
More file actions
71 lines (66 loc) · 2.02 KB
/
Copy patherrors_auth_test.go
File metadata and controls
71 lines (66 loc) · 2.02 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
package dbimp_test
import (
"errors"
"fmt"
"net/http"
"testing"
"github.com/xo/dbimp"
)
func TestStatusErrorMatchesAuthenticationFor401(t *testing.T) {
t.Parallel()
for _, tt := range []struct {
code int
want bool
}{
{http.StatusUnauthorized, true},
{http.StatusForbidden, false},
{http.StatusBadRequest, false},
{http.StatusInternalServerError, false},
} {
err := fmt.Errorf("reading: %w", errors.Join(errors.New("other"), &dbimp.StatusError{Code: tt.code}))
if got := errors.Is(err, dbimp.ErrAuthentication); got != tt.want {
t.Errorf("errors.Is for HTTP %d is %t, want %t", tt.code, got, tt.want)
}
}
if errors.Is(&dbimp.StatusError{Code: http.StatusUnauthorized}, dbimp.ErrNotSupported) {
t.Error("a 401 matches ErrNotSupported")
}
}
// refuser is the interface that a caller declares for itself, as usql does
// (D227).
type refuser interface {
AuthenticationRefused() bool
}
func TestRootErrorsSayWhetherTheServerRefusedTheCredential(t *testing.T) {
t.Parallel()
for _, tt := range []struct {
name string
err refuser
want bool
}{
{"ErrAuthentication", dbimp.ErrAuthentication, true},
{"ErrNotSupported", dbimp.ErrNotSupported, false},
{"401", &dbimp.StatusError{Code: http.StatusUnauthorized}, true},
{"403", &dbimp.StatusError{Code: http.StatusForbidden}, false},
{"500", &dbimp.StatusError{Code: http.StatusInternalServerError}, false},
} {
if got := tt.err.AuthenticationRefused(); got != tt.want {
t.Errorf("%s: AuthenticationRefused is %t, want %t", tt.name, got, tt.want)
}
}
// a wrapped sentinel stays visible to a caller that walks the tree
err := fmt.Errorf("%w: %w", dbimp.ErrAuthentication, errors.New("token refused"))
joined, ok := err.(interface{ Unwrap() []error })
if !ok {
t.Fatalf("%T has no method Unwrap() []error", err)
}
var found bool
for _, e := range joined.Unwrap() {
if r, ok := e.(refuser); ok && r.AuthenticationRefused() {
found = true
}
}
if !found {
t.Error("no error in the tree of a wrapped ErrAuthentication refuses the credential")
}
}