-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrequest_test.go
More file actions
163 lines (152 loc) · 4.57 KB
/
request_test.go
File metadata and controls
163 lines (152 loc) · 4.57 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
package httpsuite
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"github.com/stretchr/testify/assert"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
)
// TestRequest includes custom type annotation for UUID type.
type TestRequest struct {
ID int `json:"id" validate:"required,gt=0"`
Name string `json:"name" validate:"required"`
}
func (r *TestRequest) SetParam(fieldName, value string) error {
switch strings.ToLower(fieldName) {
case "id":
id, err := strconv.Atoi(value)
if err != nil {
return errors.New("invalid id")
}
r.ID = id
default:
fmt.Printf("Parameter %s cannot be set", fieldName)
}
return nil
}
// MyParamExtractor extracts parameters from the path, assuming the request URL follows a pattern like "/test/{id}".
func MyParamExtractor(r *http.Request, key string) string {
pathSegments := strings.Split(r.URL.Path, "/")
if len(pathSegments) > 2 && key == "ID" {
return pathSegments[2]
}
return ""
}
func Test_ParseRequest(t *testing.T) {
type args struct {
w http.ResponseWriter
r *http.Request
pathParams []string
}
type testCase[T any] struct {
name string
args args
want *TestRequest
wantErr assert.ErrorAssertionFunc
wantDetail *ProblemDetails
}
tests := []testCase[TestRequest]{
{
name: "Successful Request",
args: args{
w: httptest.NewRecorder(),
r: func() *http.Request {
body, _ := json.Marshal(TestRequest{Name: "Test"})
req := httptest.NewRequest("POST", "/test/123", bytes.NewBuffer(body))
req.URL.Path = "/test/123"
return req
}(),
pathParams: []string{"ID"},
},
want: &TestRequest{ID: 123, Name: "Test"},
wantErr: assert.NoError,
wantDetail: nil,
},
{
name: "Body Only - No URL Params",
args: args{
w: httptest.NewRecorder(),
r: func() *http.Request {
body, _ := json.Marshal(TestRequest{ID: 42, Name: "OnlyBody"})
req := httptest.NewRequest("POST", "/test", bytes.NewBuffer(body))
return req
}(),
pathParams: []string{},
},
want: &TestRequest{ID: 42, Name: "OnlyBody"},
wantErr: assert.NoError,
},
{
name: "Body Only - Nil Path Params",
args: args{
w: httptest.NewRecorder(),
r: func() *http.Request {
body, _ := json.Marshal(TestRequest{ID: 7, Name: "NilPathParams"})
req := httptest.NewRequest("POST", "/test", bytes.NewBuffer(body))
return req
}(),
pathParams: nil,
},
want: &TestRequest{ID: 7, Name: "NilPathParams"},
wantErr: assert.NoError,
},
{
name: "Missing body",
args: args{
w: httptest.NewRecorder(),
r: httptest.NewRequest("POST", "/test/123", nil),
pathParams: []string{"ID"},
},
want: nil,
wantErr: assert.Error,
wantDetail: NewProblemDetails(http.StatusBadRequest, "about:blank", "Validation Error",
"One or more fields failed validation."),
},
{
name: "Invalid JSON Body",
args: args{
w: httptest.NewRecorder(),
r: func() *http.Request {
req := httptest.NewRequest("POST", "/test/123", bytes.NewBufferString("{invalid-json}"))
req.URL.Path = "/test/123"
return req
}(),
pathParams: []string{"ID"},
},
want: nil,
wantErr: assert.Error,
wantDetail: NewProblemDetails(http.StatusBadRequest, "about:blank", "Invalid Request",
"invalid character 'i' looking for beginning of object key string"),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Call the function under test.
w := tt.args.w
got, err := ParseRequest[*TestRequest](w, tt.args.r, MyParamExtractor, tt.args.pathParams...)
// Validate the error response if applicable.
if !tt.wantErr(t, err, fmt.Sprintf("parseRequest(%v, %v, %v)", tt.args.w, tt.args.r, tt.args.pathParams)) {
return
}
// Check ProblemDetails if an error was expected.
if tt.wantDetail != nil {
rec := w.(*httptest.ResponseRecorder)
assert.Equal(t, "application/problem+json; charset=utf-8",
rec.Header().Get("Content-Type"), "Content-Type header mismatch")
var pd ProblemDetails
decodeErr := json.NewDecoder(rec.Body).Decode(&pd)
assert.NoError(t, decodeErr, "Failed to decode problem details response")
assert.Equal(t, tt.wantDetail.Title, pd.Title, "Problem detail title mismatch")
assert.Equal(t, tt.wantDetail.Status, pd.Status, "Problem detail status mismatch")
assert.Contains(t, pd.Detail, tt.wantDetail.Detail, "Problem detail message mismatch")
}
// Validate successful response.
assert.Equalf(t, tt.want, got, "parseRequest(%v, %v, %v)", w, tt.args.r, tt.args.pathParams)
})
}
}