diff --git a/.github/docs/openapi3.txt b/.github/docs/openapi3.txt index 80909520a..1ae20934f 100644 --- a/.github/docs/openapi3.txt +++ b/.github/docs/openapi3.txt @@ -134,6 +134,9 @@ type AdditionalProperties struct { func (addProps AdditionalProperties) MarshalJSON() ([]byte, error) MarshalJSON returns the JSON encoding of AdditionalProperties. +func (addProps AdditionalProperties) MarshalYAML() (interface{}, error) + MarshalYAML returns the YAML encoding of AdditionalProperties. + func (addProps *AdditionalProperties) UnmarshalJSON(data []byte) error UnmarshalJSON sets AdditionalProperties to a copy of data. diff --git a/openapi3/additionalProperties_test.go b/openapi3/additionalProperties_test.go new file mode 100644 index 000000000..7a9ec7473 --- /dev/null +++ b/openapi3/additionalProperties_test.go @@ -0,0 +1,40 @@ +package openapi3_test + +import ( + "bytes" + "context" + "os" + "testing" + + "github.com/stretchr/testify/require" + "gopkg.in/yaml.v3" + + "github.com/getkin/kin-openapi/openapi3" +) + +func TestMarshalAdditionalProperties(t *testing.T) { + ctx := context.Background() + data, err := os.ReadFile("testdata/test.openapi.additionalproperties.yml") + require.NoError(t, err) + + loader := openapi3.NewLoader() + loader.IsExternalRefsAllowed = true + spec, err := loader.LoadFromData(data) + require.NoError(t, err) + + err = spec.Validate(ctx) + require.NoError(t, err) + + var buf bytes.Buffer + enc := yaml.NewEncoder(&buf) + enc.SetIndent(2) + err = enc.Encode(spec) + require.NoError(t, err) + + // Load the doc from the serialized yaml. + spec2, err := loader.LoadFromData(buf.Bytes()) + require.NoError(t, err) + + err = spec2.Validate(ctx) + require.NoError(t, err) +} diff --git a/openapi3/schema.go b/openapi3/schema.go index 1b767f8fe..ae28afef7 100644 --- a/openapi3/schema.go +++ b/openapi3/schema.go @@ -213,6 +213,20 @@ type AdditionalProperties struct { Schema *SchemaRef } +// MarshalYAML returns the YAML encoding of AdditionalProperties. +func (addProps AdditionalProperties) MarshalYAML() (interface{}, error) { + if x := addProps.Has; x != nil { + if *x { + return true, nil + } + return false, nil + } + if x := addProps.Schema; x != nil { + return x.Value, nil + } + return nil, nil +} + // MarshalJSON returns the JSON encoding of AdditionalProperties. func (addProps AdditionalProperties) MarshalJSON() ([]byte, error) { if x := addProps.Has; x != nil { diff --git a/openapi3/testdata/test.openapi.additionalproperties.yml b/openapi3/testdata/test.openapi.additionalproperties.yml new file mode 100644 index 000000000..cfd078aa0 --- /dev/null +++ b/openapi3/testdata/test.openapi.additionalproperties.yml @@ -0,0 +1,17 @@ +openapi: 3.0.0 +info: + title: "OAI Specification in YAML" + version: 0.0.1 +paths: {} +components: + schemas: + TestSchema: + type: object + additionalProperties: + type: array + items: + type: string + TestSchema2: + type: object + additionalProperties: + type: string