Debian Codegraph @

tpl/openapi/openapi3/openapi3_integration_test.go

raw
1 // Copyright 2021 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package openapi3_test
15
16 import (
17 "fmt"
18 "net/http"
19 "net/http/httptest"
20 "strings"
21 "testing"
22 "time"
23
24 "github.com/gohugoio/hugo/hugolib"
25 )
26
27 func TestUnmarshal(t *testing.T) {
28 t.Parallel()
29
30 files := `
31 -- assets/api/myapi.yaml --
32 openapi: 3.0.0
33 info:
34 title: Sample API
35 description: Optional multiline or single-line description in [CommonMark](http://commonmark.org/help/) or HTML.
36 version: 0.1.9
37 servers:
38 - url: http://api.example.com/v1
39 description: Optional server description, e.g. Main (production) server
40 - url: http://staging-api.example.com
41 description: Optional server description, e.g. Internal staging server for testing
42 paths:
43 /users:
44 get:
45 summary: Returns a list of users.
46 description: Optional extended description in CommonMark or HTML.
47 responses:
48 '200': # status code
49 description: A JSON array of user names
50 content:
51 application/json:
52 schema:
53 type: array
54 items:
55 type: string
56 -- hugo.toml --
57 baseURL = 'http://example.com/'
58 disableLiveReload = true
59 -- layouts/home.html --
60 {{ $api := resources.Get "api/myapi.yaml" | openapi3.Unmarshal }}
61 API: {{ $api.Info.Title | safeHTML }}
62 `
63
64 b := hugolib.TestRunning(t, files)
65
66 b.AssertFileContent("public/index.html", `API: Sample API`)
67
68 b.
69 EditFileReplaceFunc("assets/api/myapi.yaml", func(s string) string { return strings.ReplaceAll(s, "Sample API", "Hugo API") }).
70 Build()
71
72 b.AssertFileContent("public/index.html", `API: Hugo API`)
73 }
74
75 // Test data borrowed/adapted from https://github.com/getkin/kin-openapi/tree/master/openapi3/testdata/refInLocalRef
76 // The templates below would be simpler if kin-openapi's T would serialize to JSON better, see https://github.com/getkin/kin-openapi/issues/561
77 const refLocalTemplate = `
78 -- hugo.toml --
79 baseURL = 'http://example.com/'
80 disableKinds = ["page", "section", "taxonomy", "term", "sitemap", "robotsTXT", "404"]
81 disableLiveReload = true
82 [HTTPCache]
83 [HTTPCache.cache]
84 [HTTPCache.cache.for]
85 includes = ['**']
86 [[HTTPCache.polls]]
87 high = '100ms'
88 low = '50ms'
89 [HTTPCache.polls.for]
90 includes = ['**']
91 -- assets/api/myapi.json --
92 {
93 "openapi": "3.0.3",
94 "info": {
95 "title": "Reference in reference example",
96 "version": "1.0.0"
97 },
98 "paths": {
99 "/api/test/ref/in/ref": {
100 "post": {
101 "requestBody": {
102 "content": {
103 "application/json": {
104 "schema": {
105 "type": "object",
106 "properties" : {
107 "data": {
108 "$ref": "#/components/schemas/Request"
109 }
110 }
111 }
112 }
113 }
114 },
115 "responses": {
116 "200": {
117 "description": "Successful response",
118 "content": {
119 "application/json": {
120 "schema": {
121 "$ref": "messages/response.json"
122 }
123 }
124 }
125 }
126 }
127 }
128 }
129 },
130 "components": {
131 "schemas": {
132 "Request": {
133 "$ref": "messages/request.json"
134 }
135 }
136 }
137 }
138 -- assets/api/messages/request.json --
139 {
140 "type": "object",
141 "required": [
142 "definition_reference"
143 ],
144 "properties": {
145 "definition_reference": {
146 "$ref": "./data.json"
147 }
148 }
149 }
150 -- assets/api/messages/response.json --
151 {
152 "type": "object",
153 "properties": {
154 "id": {
155 "type": "integer",
156 "format": "uint64"
157 }
158 }
159 }
160 -- assets/api/messages/data.json --
161 {
162 "type": "object",
163 "properties": {
164 "id": {
165 "type": "integer",
166 "format": "int32"
167 },
168 "ref_prop_part": {
169 "$ref": "DATAPART_REF"
170 }
171 }
172 }
173 -- assets/api/messages/dataPart.json --
174 {
175 "type": "object",
176 "properties": {
177 "idPart": {
178 "type": "integer",
179 "format": "int64"
180 }
181 }
182 }
183 -- layouts/home.html --
184 {{ $getremote := dict
185 "method" "post"
186 "key" time.Now.UnixNano
187 }}
188 {{ $opts := dict
189 "getremote" $getremote
190 }}
191 {{ with resources.Get "api/myapi.json" }}
192 {{ with openapi3.Unmarshal . $opts }}
193 Title: {{ .Info.Title | safeHTML }}
194 {{ range $k, $v := .Paths.Map }}
195 {{ $post := index $v.Post }}
196 {{ with index $post.RequestBody.Value.Content }}
197 {{ $mt := (index . "application/json")}}
198 {{ $data := index $mt.Schema.Value.Properties "data" }}
199 RequestBody: {{ template "printschema" $mt.Schema.Value }}$
200 {{ end }}
201 {{ $response := index (index $post.Responses.Map "200").Value.Content "application/json" }}
202 Response: {{ template "printschema" $response.Schema.Value }}
203 {{ end }}
204 {{ end }}
205 {{ end }}
206 {{ define "printschema" }}{{ with .Format}}Format: {{ . }}|{{ end }}{{ with .Properties }} Properties: {{ range $k, $v := . }}{{ $k}}: {{ template "printitems" . -}}{{ end }}{{ end -}}${{ end }}
207 {{ define "printitems" }}{{ if eq (printf "%T" .) "*openapi3.SchemaRef" }}{{ template "printschema" .Value }}{{ else }}{{ template "printitem" . -}}{{ end -}}{{ end }}
208 {{ define "printitem" }}{{ printf "%T: %s" . (.|debug.Dump) | safeHTML }}{{ end }}
209
210 `
211
212 func TestUnmarshalRefLocal(t *testing.T) {
213 files := strings.ReplaceAll(refLocalTemplate, "DATAPART_REF", "./dataPart.json")
214
215 b := hugolib.Test(t, files)
216
217 b.AssertFileContent("public/index.html",
218 `Reference in reference example`,
219 "RequestBody: Properties: data: Properties: definition_reference: Properties: id: Format: int32|$ref_prop_part: Properties: idPart: Format: int64|$",
220 "Response: Properties: id: Format: uint64|$",
221 )
222 }
223
224 func TestUnmarshalRefLocalEdit(t *testing.T) {
225 files := strings.ReplaceAll(refLocalTemplate, "DATAPART_REF", "./dataPart.json")
226
227 b := hugolib.TestRunning(t, files)
228
229 b.AssertFileContent("public/index.html",
230 "RequestBody: Properties: data: Properties: definition_reference: Properties: id: Format: int32|$ref_prop_part: Properties: idPart: Format: int64|$",
231 )
232
233 b.EditFileReplaceAll("assets/api/messages/dataPart.json", "int64", "int8").Build()
234
235 b.AssertFileContent("public/index.html",
236 "RequestBody: Properties: data: Properties: definition_reference: Properties: id: Format: int32|$ref_prop_part: Properties: idPart: Format: int8|$",
237 )
238 }
239
240 func TestUnmarshalRefRemote(t *testing.T) {
241 createFiles := func(t *testing.T) string {
242 counter := 0
243 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
244 if r.Method == "POST" && r.URL.Path == "/api/messages/dataPart.json" {
245 n := 8
246
247 // This endpoint will also be called by the poller, so we distinguish
248 // between the first and subsequent calls.
249 if counter > 0 {
250 n = 16
251 }
252 counter++
253
254 w.Header().Set("Content-Type", "application/json")
255 response := fmt.Sprintf(`{
256 "type": "object",
257 "properties": {
258 "idPart": {
259 "type": "integer",
260 "format": "int%d"
261 }
262 }
263 }`, n)
264 w.Write([]byte(response))
265 return
266 }
267
268 http.Error(w, "Not found", http.StatusNotFound)
269 }))
270
271 t.Cleanup(func() {
272 ts.Close()
273 })
274
275 dataPartRef := ts.URL + "/api/messages/dataPart.json"
276 files := strings.ReplaceAll(refLocalTemplate, "DATAPART_REF", dataPartRef)
277 return strings.Replace(files, "baseURL = 'http://example.com/'",
278 "baseURL = 'http://example.com/'\n[security.http]\nurls = ['.*']", 1)
279 }
280
281 t.Run("Build", func(t *testing.T) {
282 b := hugolib.Test(t, createFiles(t))
283
284 b.AssertFileContent("public/index.html",
285 `Reference in reference example`,
286 "RequestBody: Properties: data: Properties: definition_reference: Properties: id: Format: int32|$ref_prop_part: Properties: idPart: Format: int8|$",
287 "Response: Properties: id: Format: uint64|$",
288 )
289 })
290
291 t.Run("Rebuild", func(t *testing.T) {
292 b := hugolib.TestRunning(t, createFiles(t))
293
294 b.AssertFileContent("public/index.html",
295 "idPart: Format: int8|$",
296 )
297
298 // Rebuild triggered by remote polling.
299 time.Sleep(800 * time.Millisecond)
300
301 b.AssertFileContent("public/index.html",
302 "idPart: Format: int16|$",
303 )
304 })
305 }