-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmiddleware_query_test.go
57 lines (48 loc) · 1.49 KB
/
middleware_query_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 TestQueryValidator(t *testing.T) {
testCases := map[string]struct {
query string
expectedStatus int
expectedBody string
}{
"valid query": {
query: "username=johndoe&password=123",
expectedStatus: http.StatusOK,
expectedBody: "username: johndoe, password: 123",
},
"missing required query parameter": {
query: "username=johndoe",
expectedStatus: http.StatusBadRequest,
expectedBody: `{"errors":[{"message":"param password is required","field":"password"}]}`,
},
}
doc := loadDocFile(t, "testdata/petstore_1.yml")
params := doc.Analyzer.ParametersFor("loginUser")
v := &queryValidator{
next: http.HandlerFunc(handleUserLogin),
problemHandler: problemHandlerResponseWriter(),
continueOnProblem: false,
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/v2/user/login?"+tc.query, nil)
w := httptest.NewRecorder()
v.ServeHTTP(w, req, params, true)
assert.Equal(t, tc.expectedStatus, w.Code)
assert.Equal(t, tc.expectedBody, w.Body.String())
})
}
}
func handleUserLogin(w http.ResponseWriter, req *http.Request) {
username := req.URL.Query().Get("username")
password := req.URL.Query().Get("password")
// Never do this! This is just for testing purposes.
fmt.Fprintf(w, "username: %s, password: %s", username, password)
}