Add ‘disable required check’ switch on renderer #200

Signed-off-by: quobix <dave@quobix.com>
This commit is contained in:
quobix
2023-11-22 14:39:13 -05:00
parent ee2783e6e7
commit 0b1a147a26
2 changed files with 36 additions and 2 deletions

View File

@@ -57,7 +57,8 @@ func init() {
// SchemaRenderer is a renderer that will generate random words, numbers and values based on a dictionary file.
// The dictionary is just a slice of strings that is used to generate random words.
type SchemaRenderer struct {
words []string
words []string
disableRequired bool
}
// CreateRendererUsingDictionary will create a new SchemaRenderer using a custom dictionary file.
@@ -85,6 +86,13 @@ func (wr *SchemaRenderer) RenderSchema(schema *base.Schema) any {
return structure[rootType].(any)
}
// DisableRequiredCheck will disable the required check when rendering a schema. This means that all properties
// will be rendered, not just the required ones.
// https://github.com/pb33f/libopenapi/issues/200
func (wr *SchemaRenderer) DisableRequiredCheck() {
wr.disableRequired = true
}
// DiveIntoSchema will dive into a schema and inject values from examples into a map. If there are no examples in
// the schema, then the renderer will attempt to generate a value based on the schema type, format and pattern.
func (wr *SchemaRenderer) DiveIntoSchema(schema *base.Schema, key string, structure map[string]any, depth int) {
@@ -219,7 +227,7 @@ func (wr *SchemaRenderer) DiveIntoSchema(schema *base.Schema, key string, struct
// check if this schema has required properties, if so, then only render required props, if not
// render everything in the schema.
checkProps := make(map[string]*base.SchemaProxy)
if len(schema.Required) > 0 {
if !wr.disableRequired && len(schema.Required) > 0 {
for _, requiredProp := range schema.Required {
checkProps[requiredProp] = properties[requiredProp]
}

View File

@@ -960,6 +960,32 @@ properties:
assert.Nil(t, journeyMap["pb33f"].(map[string]interface{})["fries"])
}
func TestRenderExample_Test_RequiredCheckDisabled(t *testing.T) {
testObject := `type: [object]
required:
- drink
properties:
burger:
type: string
fries:
type: string
drink:
type: string`
compiled := getSchema([]byte(testObject))
journeyMap := make(map[string]any)
wr := createSchemaRenderer()
wr.DisableRequiredCheck()
wr.DiveIntoSchema(compiled, "pb33f", journeyMap, 0)
assert.NotNil(t, journeyMap["pb33f"])
drink := journeyMap["pb33f"].(map[string]interface{})["drink"].(string)
assert.NotNil(t, drink)
assert.NotNil(t, journeyMap["pb33f"].(map[string]interface{})["burger"])
assert.NotNil(t, journeyMap["pb33f"].(map[string]interface{})["fries"])
}
func TestRenderSchema_WithExample(t *testing.T) {
testObject := `type: [object]
properties: