From 5f48b58366f7ba49d153374f042314e1392141f9 Mon Sep 17 00:00:00 2001 From: Shreyas Goenka Date: Mon, 9 Sep 2024 11:18:07 +0200 Subject: [PATCH] add test for bfs final schema --- libs/jsonschema/from_type.go | 7 ++++++ libs/jsonschema/from_type_test.go | 41 +++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/libs/jsonschema/from_type.go b/libs/jsonschema/from_type.go index 30e70c10..7a001246 100644 --- a/libs/jsonschema/from_type.go +++ b/libs/jsonschema/from_type.go @@ -272,6 +272,13 @@ func (c *constructor) fromTypeStruct(typ reflect.Type) (Schema, error) { continue } + // Skip property if it is already present in the schema. + // This can happen if the same field is defined multiple times across + // a tree of embedded structs. For example see: TestHigherLevelEmbeddedFieldIsInSchema + if _, ok := res.Properties[fieldName]; ok { + continue + } + // "omitempty" tags in the Go SDK structs represent fields that not are // required to be present in the API payload. Thus its absence in the // tags list indicates that the field is required. diff --git a/libs/jsonschema/from_type_test.go b/libs/jsonschema/from_type_test.go index 4f5c5524..174ffad8 100644 --- a/libs/jsonschema/from_type_test.go +++ b/libs/jsonschema/from_type_test.go @@ -6,6 +6,7 @@ import ( "github.com/databricks/cli/libs/jsonschema/test_types" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestFromTypeBasic(t *testing.T) { @@ -166,6 +167,46 @@ func TestGetStructFields(t *testing.T) { assert.Equal(t, "InnerField", fields[3].Name) } +func TestHigherLevelEmbeddedFieldIsInSchema(t *testing.T) { + type Inner struct { + Override string `json:"override,omitempty"` + } + + type EmbeddedOne struct { + Inner + } + + type EmbeddedTwo struct { + Override int `json:"override,omitempty"` + } + + type Outer struct { + EmbeddedOne + EmbeddedTwo + } + + intRef := "#/$defs/int" + expected := Schema{ + Type: "object", + Definitions: map[string]any{ + "int": Schema{ + Type: "integer", + }, + }, + Properties: map[string]*Schema{ + "override": { + Reference: &intRef, + }, + }, + AdditionalProperties: false, + Required: []string{}, + } + + s, err := FromType(reflect.TypeOf(Outer{}), nil) + require.NoError(t, err) + assert.Equal(t, expected, s) +} + func TestFromTypeNested(t *testing.T) { type Inner struct { S string `json:"s"`