-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrequest_bind_test.go
More file actions
77 lines (69 loc) · 2.33 KB
/
request_bind_test.go
File metadata and controls
77 lines (69 loc) · 2.33 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
package httpsuite
import (
"errors"
"net/http"
"net/http/httptest"
"testing"
)
func TestBindPathParams(t *testing.T) {
t.Parallel()
t.Run("nil request pointer target", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/test/123", nil)
got, err := BindPathParams[*testRequest](nil, req, testParamExtractor, "id")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got == nil || got.ID != 123 {
t.Fatalf("expected initialized request target, got %#v", got)
}
})
t.Run("unsupported request target", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/test/123", nil)
_, err := BindPathParams[bodyOnlyRequest](bodyOnlyRequest{}, req, testParamExtractor, "id")
if err == nil {
t.Fatal("expected error, got nil")
}
if errors.Is(err, errNilHTTPRequest) || errors.Is(err, errNilParamExtractor) {
t.Fatalf("expected unsupported target error, got %v", err)
}
})
t.Run("nil extractor", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/test/123", nil)
_, err := BindPathParams[*testRequest](&testRequest{}, req, nil, "id")
if !errors.Is(err, errNilParamExtractor) {
t.Fatalf("expected nil extractor error, got %v", err)
}
})
t.Run("valid parameter", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/test/123", nil)
got, err := BindPathParams[*testRequest](&testRequest{Name: "ok"}, req, testParamExtractor, "id")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got.ID != 123 {
t.Fatalf("expected id 123, got %d", got.ID)
}
})
t.Run("missing parameter", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/test", nil)
_, err := BindPathParams[*testRequest](&testRequest{}, req, testParamExtractor, "id")
var pathErr *PathParamError
if !errors.As(err, &pathErr) {
t.Fatalf("expected PathParamError, got %v", err)
}
if !pathErr.Missing {
t.Fatalf("expected missing parameter error")
}
})
t.Run("invalid parameter", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/test/nope", nil)
_, err := BindPathParams[*testRequest](&testRequest{}, req, testParamExtractor, "id")
var pathErr *PathParamError
if !errors.As(err, &pathErr) {
t.Fatalf("expected PathParamError, got %v", err)
}
if pathErr.Missing {
t.Fatalf("expected invalid parameter, got missing")
}
})
}