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