-
Notifications
You must be signed in to change notification settings - Fork 5
/
middleware_path_params_test.go
57 lines (48 loc) · 1.27 KB
/
middleware_path_params_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
package oas
import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
)
func TestPathParamsExtractor(t *testing.T) {
testCases := map[string]struct {
url string
extractor func(req *http.Request, key string) string
expectedStatus int
expectedBody string
}{
"extracts parameters": {
url: "/v2/pet/12",
extractor: func(req *http.Request, key string) string {
return "12"
},
expectedStatus: http.StatusOK,
expectedBody: "pet by id: 12",
},
}
doc := loadDocFile(t, "testdata/petstore_1.yml")
params := doc.Analyzer.ParametersFor("getPetById")
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
h := &pathParamExtractor{
next: http.HandlerFunc(handleGetPetByID),
extractor: PathParamExtractorFunc(tc.extractor),
}
req := httptest.NewRequest(http.MethodGet, tc.url, nil)
w := httptest.NewRecorder()
h.ServeHTTP(w, req, params, true)
assert.Equal(t, tc.expectedStatus, w.Code)
assert.Equal(t, tc.expectedBody, w.Body.String())
})
}
}
func handleGetPetByID(w http.ResponseWriter, req *http.Request) {
id, ok := GetPathParam(req, "petId").(int64)
if !ok {
w.WriteHeader(http.StatusNotFound)
return
}
fmt.Fprintf(w, "pet by id: %d", id)
}