Skip to content

Commit

Permalink
reproduce incorrect discriminator handling with ValidateRequest (#323)
Browse files Browse the repository at this point in the history
  • Loading branch information
fenollp authored Mar 10, 2021
1 parent 1286d06 commit 0ef6b18
Showing 1 changed file with 108 additions and 0 deletions.
108 changes: 108 additions & 0 deletions openapi3filter/validate_request_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
package openapi3filter_test

import (
"bytes"
"encoding/json"
"fmt"
"net/http"

"github.com/getkin/kin-openapi/openapi3"
"github.com/getkin/kin-openapi/openapi3filter"
)

const spec = `
openapi: 3.0.0
info:
title: My API
version: 0.0.1
paths:
/:
post:
responses:
default:
description: ''
requestBody:
required: true
content:
application/json:
schema:
oneOf:
- $ref: '#/components/schemas/Cat'
- $ref: '#/components/schemas/Dog'
discriminator:
propertyName: pet_type
components:
schemas:
Pet:
type: object
required: [pet_type]
properties:
pet_type:
type: string
discriminator:
propertyName: pet_type
Dog:
allOf:
- $ref: '#/components/schemas/Pet'
- type: object
properties:
breed:
type: string
enum: [Dingo, Husky, Retriever, Shepherd]
Cat:
allOf:
- $ref: '#/components/schemas/Pet'
- type: object
properties:
hunts:
type: boolean
age:
type: integer
`

func Example() {
loader := openapi3.NewSwaggerLoader()
doc, err := loader.LoadSwaggerFromData([]byte(spec))
if err != nil {
panic(err)
}
if err := doc.Validate(loader.Context); err != nil {
panic(err)
}

router := openapi3filter.NewRouter().WithSwagger(doc)

p, err := json.Marshal(map[string]interface{}{
"pet_type": "Cat",
"breed": "Dingo",
"bark": true,
})
if err != nil {
panic(err)
}

req, err := http.NewRequest(http.MethodPost, "/", bytes.NewReader(p))
if err != nil {
panic(err)
}
req.Header.Set("Content-Type", "application/json")

route, pathParams, err := router.FindRoute(req.Method, req.URL)
if err != nil {
panic(err)
}

requestValidationInput := &openapi3filter.RequestValidationInput{
Request: req,
PathParams: pathParams,
Route: route,
}
if err = openapi3filter.ValidateRequest(loader.Context, requestValidationInput); err == nil {
fmt.Println("Valid")
} else {
fmt.Println("NOT valid")
}
// Output: NOT valid
}

0 comments on commit 0ef6b18

Please sign in to comment.