From 626bca5ee4b83b7432808bfa4beb69fc5044000f Mon Sep 17 00:00:00 2001 From: Thomas Rooney Date: Thu, 13 Jun 2024 12:10:54 +0100 Subject: [PATCH] fix: render empty scalar nodes --- datamodel/high/node_builder.go | 7 +++++++ datamodel/high/v3/document_test.go | 19 +++++++++++++++++++ test_specs/nullable-examples.openapi.yaml | 14 ++++++++++++++ utils/nodes.go | 9 +++++++++ 4 files changed, 49 insertions(+) create mode 100644 test_specs/nullable-examples.openapi.yaml diff --git a/datamodel/high/node_builder.go b/datamodel/high/node_builder.go index f2de077..b377ad6 100644 --- a/datamodel/high/node_builder.go +++ b/datamodel/high/node_builder.go @@ -513,6 +513,13 @@ func (n *NodeBuilder) AddYAMLNode(parent *yaml.Node, entry *nodes.NodeEntry) *ya valueNode.Line = line } } + if b, bok := value.(*yaml.Node); bok { + if b.Kind == yaml.ScalarNode && b.Tag == "!!null" { + encodeSkip = true + valueNode = utils.CreateEmptyScalarNode() + valueNode.Line = line + } + } if !encodeSkip { var rawNode yaml.Node err := rawNode.Encode(value) diff --git a/datamodel/high/v3/document_test.go b/datamodel/high/v3/document_test.go index 948b982..f29ee57 100644 --- a/datamodel/high/v3/document_test.go +++ b/datamodel/high/v3/document_test.go @@ -635,6 +635,25 @@ func TestDocument_MarshalIndention(t *testing.T) { } } +func TestDocument_Nullable_Example(t *testing.T) { + data, _ := os.ReadFile("../../../test_specs/nullable-examples.openapi.yaml") + info, _ := datamodel.ExtractSpecInfo(data) + + lowDoc, _ = lowv3.CreateDocumentFromConfig(info, datamodel.NewDocumentConfiguration()) + + highDoc := NewDocument(lowDoc) + rendered := highDoc.RenderWithIndention(2) + + if runtime.GOOS != "windows" { + assert.Equal(t, string(data), strings.TrimSpace(string(rendered))) + } + + rendered = highDoc.RenderWithIndention(4) + if runtime.GOOS != "windows" { + assert.NotEqual(t, string(data), strings.TrimSpace(string(rendered))) + } +} + func TestDocument_MarshalIndention_Error(t *testing.T) { data, _ := os.ReadFile("../../../test_specs/single-definition.yaml") info, _ := datamodel.ExtractSpecInfo(data) diff --git a/test_specs/nullable-examples.openapi.yaml b/test_specs/nullable-examples.openapi.yaml new file mode 100644 index 0000000..2df0192 --- /dev/null +++ b/test_specs/nullable-examples.openapi.yaml @@ -0,0 +1,14 @@ +openapi: 3.1.0 +components: + schemas: + Thing: + type: object + description: A nullable example. + properties: + target: + nullable: true + type: string + enum: + - staging + - production + example: \ No newline at end of file diff --git a/utils/nodes.go b/utils/nodes.go index 07a2d81..153c2bf 100644 --- a/utils/nodes.go +++ b/utils/nodes.go @@ -67,6 +67,15 @@ func CreateIntNode(str string) *yaml.Node { return n } +func CreateEmptyScalarNode() *yaml.Node { + n := &yaml.Node{ + Kind: yaml.ScalarNode, + Tag: "!!null", + Value: "", + } + return n +} + func CreateFloatNode(str string) *yaml.Node { n := &yaml.Node{ Kind: yaml.ScalarNode,