-
Notifications
You must be signed in to change notification settings - Fork 5
/
decode_integration_test.go
120 lines (95 loc) · 2.41 KB
/
decode_integration_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
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
package oas_test
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/hypnoglow/oas2"
)
func TestDecodeQueryParams(t *testing.T) {
doc, err := oas.LoadFile(getSpecPath(t))
assert.NoError(t, err)
oas.RegisterAdapter("fake", fakeAdapter{})
basis := oas.NewResolvingBasis("fake", doc)
h := basis.OperationContext()(getPetsHandler{})
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/pets", nil)
h.ServeHTTP(w, req)
var result struct {
Limit int64 `json:"limit"`
}
assert.Equal(t, http.StatusOK, w.Code)
if err = json.NewDecoder(w.Body).Decode(&result); err != nil {
t.Fatalf("Unexpected error: %v", err)
}
assert.EqualValues(t, 10, result.Limit)
}
type fakeAdapter struct{}
func (fakeAdapter) Resolver(meta interface{}) oas.Resolver {
return fakeResolver{}
}
func (fakeAdapter) OperationRouter(meta interface{}) oas.OperationRouter {
panic("implement me")
}
func (fakeAdapter) PathParamExtractor() oas.PathParamExtractor {
panic("implement me")
}
type fakeResolver struct{}
func (fakeResolver) Resolve(req *http.Request) (string, bool) {
return "getPets", true
}
type getPetsHandler struct{}
func (getPetsHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
var query struct {
Limit int64 `json:"limit" oas:"limit"`
}
if err := oas.DecodeQuery(req, &query); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := json.NewEncoder(w).Encode(query); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func getSpecPath(t *testing.T) string {
t.Helper()
spec := `
swagger: "2.0"
info:
title: Test API
version: 0.1.0
basePath: "/api"
paths:
/pets:
get:
summary: Find pets
operationId: getPets
parameters:
- name: limit
in: query
required: false
type: integer
format: int64
default: 10
responses:
200:
description: Pets found
schema:
type: object
properties:
limit:
title: Requested limit
type: integer
format: int64
500:
description: "Internal Server Error"
`
p := "/tmp/spec.yaml"
// write to file
if err := ioutil.WriteFile(p, []byte(spec), 0755); err != nil {
t.Fatalf("Unexpected error: %v", err)
}
return p
}