| 1 |
// Copyright 2023-2025 Princess Beef Heavy Industries, LLC / Dave Shanley |
| 2 |
// SPDX-License-Identifier: MIT |
| 3 |
|
| 4 |
package validator |
| 5 |
|
| 6 |
import ( |
| 7 |
"encoding/json" |
| 8 |
"fmt" |
| 9 |
"net/http" |
| 10 |
"net/http/httptest" |
| 11 |
"os" |
| 12 |
|
| 13 |
"github.com/pb33f/libopenapi" |
| 14 |
|
| 15 |
"github.com/pb33f/libopenapi-validator/helpers" |
| 16 |
) |
| 17 |
|
| 18 |
func ExampleNewValidator_validateDocument() { |
| 19 |
// 1. Load the OpenAPI 3+ spec into a byte array |
| 20 |
petstore, err := os.ReadFile("test_specs/invalid_31.yaml") |
| 21 |
if err != nil { |
| 22 |
panic(err) |
| 23 |
} |
| 24 |
|
| 25 |
// 2. Create a new OpenAPI document using libopenapi |
| 26 |
document, docErrs := libopenapi.NewDocument(petstore) |
| 27 |
|
| 28 |
if docErrs != nil { |
| 29 |
panic(docErrs) |
| 30 |
} |
| 31 |
|
| 32 |
// 3. Create a new validator |
| 33 |
docValidator, validatorErrs := NewValidator(document) |
| 34 |
|
| 35 |
if validatorErrs != nil { |
| 36 |
panic(validatorErrs) |
| 37 |
} |
| 38 |
|
| 39 |
// 4. Validate! |
| 40 |
valid, validationErrs := docValidator.ValidateDocument() |
| 41 |
|
| 42 |
if !valid { |
| 43 |
for i, e := range validationErrs { |
| 44 |
// 5. Handle the error |
| 45 |
fmt.Printf("%d: Type: %s, Failure: %s\n", i, e.ValidationType, e.Message) |
| 46 |
fmt.Printf("Fix: %s\n\n", e.HowToFix) |
| 47 |
} |
| 48 |
} |
| 49 |
// Output: 0: Type: schema, Failure: Document does not pass validation |
| 50 |
// Fix: Ensure that the object being submitted, matches the schema correctly |
| 51 |
} |
| 52 |
|
| 53 |
func ExampleNewValidator_validateHttpRequest() { |
| 54 |
// 1. Load the OpenAPI 3+ spec into a byte array |
| 55 |
petstore, err := os.ReadFile("test_specs/petstorev3.json") |
| 56 |
if err != nil { |
| 57 |
panic(err) |
| 58 |
} |
| 59 |
|
| 60 |
// 2. Create a new OpenAPI document using libopenapi |
| 61 |
document, docErrs := libopenapi.NewDocument(petstore) |
| 62 |
|
| 63 |
if docErrs != nil { |
| 64 |
panic(docErrs) |
| 65 |
} |
| 66 |
|
| 67 |
// 3. Create a new validator |
| 68 |
docValidator, validatorErrs := NewValidator(document) |
| 69 |
|
| 70 |
if validatorErrs != nil { |
| 71 |
panic(validatorErrs) |
| 72 |
} |
| 73 |
|
| 74 |
// 4. Create a new *http.Request (normally, this would be where the host application will pass in the request) |
| 75 |
// Note: /pet/{petId} requires api_key OR petstore_auth (OAuth2). Since OAuth2 is not validated, |
| 76 |
// the security check passes. The path parameter validation fails because "NotAValidPetId" is not an integer. |
| 77 |
request, _ := http.NewRequest(http.MethodGet, "/pet/NotAValidPetId", nil) |
| 78 |
|
| 79 |
// 5. Validate! |
| 80 |
valid, validationErrs := docValidator.ValidateHttpRequest(request) |
| 81 |
|
| 82 |
if !valid { |
| 83 |
for _, e := range validationErrs { |
| 84 |
// 5. Handle the error |
| 85 |
fmt.Printf("Type: %s, Failure: %s\n", e.ValidationType, e.Message) |
| 86 |
} |
| 87 |
} |
| 88 |
// Output: Type: parameter, Failure: Path parameter 'petId' is not a valid integer |
| 89 |
} |
| 90 |
|
| 91 |
func ExampleNewValidator_validateHttpRequestSync() { |
| 92 |
// 1. Load the OpenAPI 3+ spec into a byte array |
| 93 |
petstore, err := os.ReadFile("test_specs/petstorev3.json") |
| 94 |
if err != nil { |
| 95 |
panic(err) |
| 96 |
} |
| 97 |
|
| 98 |
// 2. Create a new OpenAPI document using libopenapi |
| 99 |
document, docErrs := libopenapi.NewDocument(petstore) |
| 100 |
|
| 101 |
if docErrs != nil { |
| 102 |
panic(docErrs) |
| 103 |
} |
| 104 |
|
| 105 |
// 3. Create a new validator |
| 106 |
docValidator, validatorErrs := NewValidator(document) |
| 107 |
|
| 108 |
if validatorErrs != nil { |
| 109 |
panic(validatorErrs) |
| 110 |
} |
| 111 |
|
| 112 |
// 4. Create a new *http.Request (normally, this would be where the host application will pass in the request) |
| 113 |
request, _ := http.NewRequest(http.MethodGet, "/pet/NotAValidPetId", nil) |
| 114 |
|
| 115 |
// 5. Validate! |
| 116 |
valid, validationErrs := docValidator.ValidateHttpRequestSync(request) |
| 117 |
|
| 118 |
if !valid { |
| 119 |
for _, e := range validationErrs { |
| 120 |
// 5. Handle the error |
| 121 |
fmt.Printf("Type: %s, Failure: %s\n", e.ValidationType, e.Message) |
| 122 |
} |
| 123 |
} |
| 124 |
// Output: Type: parameter, Failure: Path parameter 'petId' is not a valid integer |
| 125 |
} |
| 126 |
|
| 127 |
func ExampleNewValidator_validateHttpRequestResponse() { |
| 128 |
// 1. Load the OpenAPI 3+ spec into a byte array |
| 129 |
petstore, err := os.ReadFile("test_specs/petstorev3.json") |
| 130 |
if err != nil { |
| 131 |
panic(err) |
| 132 |
} |
| 133 |
|
| 134 |
// 2. Create a new OpenAPI document using libopenapi |
| 135 |
document, docErrs := libopenapi.NewDocument(petstore) |
| 136 |
|
| 137 |
if docErrs != nil { |
| 138 |
panic(docErrs) |
| 139 |
} |
| 140 |
|
| 141 |
// 3. Create a new validator |
| 142 |
docValidator, validatorErrs := NewValidator(document) |
| 143 |
|
| 144 |
if validatorErrs != nil { |
| 145 |
panic(validatorErrs) |
| 146 |
} |
| 147 |
|
| 148 |
// 6. Create a new *http.Request (normally, this would be where the host application will pass in the request) |
| 149 |
request, _ := http.NewRequest(http.MethodGet, "/pet/findByStatus?status=sold", nil) |
| 150 |
|
| 151 |
// 7. Simulate a request/response, in this case the contract returns a 200 with an array of pets. |
| 152 |
// Normally, this would be where the host application would pass in the response. |
| 153 |
recorder := httptest.NewRecorder() |
| 154 |
handler := func(w http.ResponseWriter, r *http.Request) { |
| 155 |
// set return content type. |
| 156 |
w.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType) |
| 157 |
w.WriteHeader(http.StatusOK) |
| 158 |
|
| 159 |
// create a Pet |
| 160 |
body := map[string]interface{}{ |
| 161 |
"id": 123, |
| 162 |
"name": "cotton", |
| 163 |
"category": map[string]interface{}{ |
| 164 |
"id": "NotAValidPetId", // this will fail, it should be an integer. |
| 165 |
"name": "dogs", |
| 166 |
}, |
| 167 |
"photoUrls": []string{"https://pb33f.io"}, |
| 168 |
} |
| 169 |
|
| 170 |
// marshal the request body into bytes. |
| 171 |
responseBodyBytes, _ := json.Marshal([]interface{}{body}) // operation returns an array of pets |
| 172 |
// return the response. |
| 173 |
_, _ = w.Write(responseBodyBytes) |
| 174 |
} |
| 175 |
|
| 176 |
// simulate request/response |
| 177 |
handler(recorder, request) |
| 178 |
|
| 179 |
// 7. Validate! |
| 180 |
valid, validationErrs := docValidator.ValidateHttpRequestResponse(request, recorder.Result()) |
| 181 |
|
| 182 |
if !valid { |
| 183 |
for _, e := range validationErrs { |
| 184 |
// 5. Handle the error |
| 185 |
fmt.Printf("Type: %s, Failure: %s\n", e.ValidationType, e.Message) |
| 186 |
fmt.Printf("Schema Error: %s, Line: %d, Col: %d\n", |
| 187 |
e.SchemaValidationErrors[0].Reason, |
| 188 |
e.SchemaValidationErrors[0].Line, |
| 189 |
e.SchemaValidationErrors[0].Column) |
| 190 |
} |
| 191 |
} |
| 192 |
// Output: Type: response, Failure: 200 response body for '/pet/findByStatus' failed to validate schema |
| 193 |
// Schema Error: got string, want integer, Line: 19, Col: 27 |
| 194 |
} |
| 195 |
|
| 196 |
func ExampleNewValidator_validateHttpResponse() { |
| 197 |
// 1. Load the OpenAPI 3+ spec into a byte array |
| 198 |
petstore, err := os.ReadFile("test_specs/petstorev3.json") |
| 199 |
if err != nil { |
| 200 |
panic(err) |
| 201 |
} |
| 202 |
|
| 203 |
// 2. Create a new OpenAPI document using libopenapi |
| 204 |
document, docErrs := libopenapi.NewDocument(petstore) |
| 205 |
|
| 206 |
if docErrs != nil { |
| 207 |
panic(docErrs) |
| 208 |
} |
| 209 |
|
| 210 |
// 3. Create a new validator |
| 211 |
docValidator, validatorErrs := NewValidator(document) |
| 212 |
|
| 213 |
if validatorErrs != nil { |
| 214 |
panic(validatorErrs) |
| 215 |
} |
| 216 |
|
| 217 |
// 6. Create a new *http.Request (normally, this would be where the host application will pass in the request) |
| 218 |
request, _ := http.NewRequest(http.MethodGet, "/pet/findByStatus?status=sold", nil) |
| 219 |
|
| 220 |
// 7. Simulate a request/response, in this case the contract returns a 200 with an array of pets. |
| 221 |
// Normally, this would be where the host application would pass in the response. |
| 222 |
recorder := httptest.NewRecorder() |
| 223 |
handler := func(w http.ResponseWriter, r *http.Request) { |
| 224 |
// set return content type. |
| 225 |
w.Header().Set(helpers.ContentTypeHeader, helpers.JSONContentType) |
| 226 |
w.WriteHeader(http.StatusOK) |
| 227 |
|
| 228 |
// create a Pet |
| 229 |
body := map[string]interface{}{ |
| 230 |
"id": 123, |
| 231 |
"name": "cotton", |
| 232 |
"category": map[string]interface{}{ |
| 233 |
"id": "NotAValidPetId", // this will fail, it should be an integer. |
| 234 |
"name": "dogs", |
| 235 |
}, |
| 236 |
"photoUrls": []string{"https://pb33f.io"}, |
| 237 |
} |
| 238 |
|
| 239 |
// marshal the request body into bytes. |
| 240 |
responseBodyBytes, _ := json.Marshal([]interface{}{body}) // operation returns an array of pets |
| 241 |
// return the response. |
| 242 |
_, _ = w.Write(responseBodyBytes) |
| 243 |
} |
| 244 |
|
| 245 |
// simulate request/response |
| 246 |
handler(recorder, request) |
| 247 |
|
| 248 |
// 7. Validate the response only |
| 249 |
valid, validationErrs := docValidator.ValidateHttpResponse(request, recorder.Result()) |
| 250 |
|
| 251 |
if !valid { |
| 252 |
for _, e := range validationErrs { |
| 253 |
// 5. Handle the error |
| 254 |
fmt.Printf("Type: %s, Failure: %s\n", e.ValidationType, e.Message) |
| 255 |
fmt.Printf("Schema Error: %s, Line: %d, Col: %d\n", |
| 256 |
e.SchemaValidationErrors[0].Reason, |
| 257 |
e.SchemaValidationErrors[0].Line, |
| 258 |
e.SchemaValidationErrors[0].Column) |
| 259 |
} |
| 260 |
} |
| 261 |
// Output: Type: response, Failure: 200 response body for '/pet/findByStatus' failed to validate schema |
| 262 |
// Schema Error: got string, want integer, Line: 19, Col: 27 |
| 263 |
} |
| 264 |
|
| 265 |
func ExampleNewValidator_testResponseHeaders() { |
| 266 |
// 1. Load the OpenAPI 3+ spec into a byte array |
| 267 |
petstore := []byte(`openapi: "3.0.0" |
| 268 |
info: |
| 269 |
title: Healthcheck |
| 270 |
version: '0.1.0' |
| 271 |
paths: |
| 272 |
/health: |
| 273 |
get: |
| 274 |
responses: |
| 275 |
'200': |
| 276 |
headers: |
| 277 |
chicken-nuggets: |
| 278 |
description: chicken nuggets response |
| 279 |
required: true |
| 280 |
schema: |
| 281 |
type: integer |
| 282 |
description: pet response`) |
| 283 |
|
| 284 |
// 2. Create a new OpenAPI document using libopenapi |
| 285 |
document, docErrs := libopenapi.NewDocument(petstore) |
| 286 |
|
| 287 |
if docErrs != nil { |
| 288 |
panic(docErrs) |
| 289 |
} |
| 290 |
|
| 291 |
// 3. Create a new validator |
| 292 |
docValidator, validatorErrs := NewValidator(document) |
| 293 |
|
| 294 |
if validatorErrs != nil { |
| 295 |
panic(validatorErrs) |
| 296 |
} |
| 297 |
|
| 298 |
// 6. Create a new *http.Request (normally, this would be where the host application will pass in the request) |
| 299 |
request, _ := http.NewRequest(http.MethodGet, "/health", nil) |
| 300 |
|
| 301 |
// 7. Simulate a request/response, in this case the contract returns a 200 with an array of pets. |
| 302 |
// Normally, this would be where the host application would pass in the response. |
| 303 |
recorder := httptest.NewRecorder() |
| 304 |
handler := func(w http.ResponseWriter, r *http.Request) { |
| 305 |
// set return content type. |
| 306 |
w.Header().Set("Chicken-Nuggets", "I am a chicken nugget, and not an integer") |
| 307 |
w.WriteHeader(http.StatusOK) |
| 308 |
_, _ = w.Write(nil) |
| 309 |
} |
| 310 |
|
| 311 |
// simulate request/response |
| 312 |
handler(recorder, request) |
| 313 |
|
| 314 |
// 7. Validate the response only |
| 315 |
valid, validationErrs := docValidator.ValidateHttpResponse(request, recorder.Result()) |
| 316 |
|
| 317 |
if !valid { |
| 318 |
for _, e := range validationErrs { |
| 319 |
// 5. Handle the error |
| 320 |
fmt.Printf("Type: %s, Failure: %s\n", e.ValidationType, e.Message) |
| 321 |
} |
| 322 |
} |
| 323 |
// Output: Type: response, Failure: header 'chicken-nuggets' failed to validate |
| 324 |
} |
| 325 |
|
| 326 |
func ExampleNewValidator_responseHeaderNotRequired() { |
| 327 |
// 1. Load the OpenAPI 3+ spec into a byte array |
| 328 |
petstore := []byte(`openapi: "3.0.0" |
| 329 |
info: |
| 330 |
title: Healthcheck |
| 331 |
version: '0.1.0' |
| 332 |
paths: |
| 333 |
/health: |
| 334 |
get: |
| 335 |
responses: |
| 336 |
'200': |
| 337 |
headers: |
| 338 |
chicken-nuggets: |
| 339 |
description: chicken nuggets response |
| 340 |
required: false |
| 341 |
schema: |
| 342 |
type: integer |
| 343 |
description: pet response`) |
| 344 |
|
| 345 |
// 2. Create a new OpenAPI document using libopenapi |
| 346 |
document, docErrs := libopenapi.NewDocument(petstore) |
| 347 |
|
| 348 |
if docErrs != nil { |
| 349 |
panic(docErrs) |
| 350 |
} |
| 351 |
|
| 352 |
// 3. Create a new validator |
| 353 |
docValidator, validatorErrs := NewValidator(document) |
| 354 |
|
| 355 |
if validatorErrs != nil { |
| 356 |
panic(validatorErrs) |
| 357 |
} |
| 358 |
|
| 359 |
// 6. Create a new *http.Request (normally, this would be where the host application will pass in the request) |
| 360 |
request, _ := http.NewRequest(http.MethodGet, "/health", nil) |
| 361 |
|
| 362 |
// 7. Simulate a request/response, in this case the contract returns a 200 with an array of pets. |
| 363 |
// Normally, this would be where the host application would pass in the response. |
| 364 |
recorder := httptest.NewRecorder() |
| 365 |
handler := func(w http.ResponseWriter, r *http.Request) { |
| 366 |
// set return content type. |
| 367 |
w.Header().Set("Chicken-Nuggets", "I am a chicken nugget, and not an integer") |
| 368 |
w.WriteHeader(http.StatusOK) |
| 369 |
_, _ = w.Write(nil) |
| 370 |
} |
| 371 |
|
| 372 |
// simulate request/response |
| 373 |
handler(recorder, request) |
| 374 |
|
| 375 |
// 7. Validate the response only |
| 376 |
valid, _ := docValidator.ValidateHttpResponse(request, recorder.Result()) |
| 377 |
|
| 378 |
if !valid { |
| 379 |
panic("the header is not required, it should not fail") |
| 380 |
} |
| 381 |
fmt.Println("Header is not required, validation passed") |
| 382 |
// Output: Header is not required, validation passed |
| 383 |
} |