Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 9 additions & 75 deletions what-changed/model/example.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,8 @@
package model

import (
"fmt"
"sort"

"github.com/pb33f/libopenapi/datamodel/low"
"github.com/pb33f/libopenapi/datamodel/low/base"
v3 "github.com/pb33f/libopenapi/datamodel/low/v3"
"github.com/pb33f/libopenapi/utils"
)

// ExampleChanges represent changes to an Example object, part of an OpenAPI specification.
Expand Down Expand Up @@ -82,82 +77,21 @@ func CompareExamples(l, r *base.Example) *ExampleChanges {
v3.DescriptionLabel, &changes, l, r),
)

// Value
if utils.IsNodeMap(l.Value.ValueNode) && utils.IsNodeMap(r.Value.ValueNode) {
if !compareYAMLNodesForChanges(l.Value.ValueNode, r.Value.ValueNode) {
lKeys := make([]string, len(l.Value.ValueNode.Content)/2)
rKeys := make([]string, len(r.Value.ValueNode.Content)/2)
z := 0
for k := range l.Value.ValueNode.Content {
if k%2 == 0 {
// if there is no value (value is another map or something else), render the node into yaml and hash it.
// https://github.com/pb33f/libopenapi/issues/61
val := l.Value.ValueNode.Content[k+1].Value
if val == "" {
val = low.HashYAMLNodeSlice(l.Value.ValueNode.Content[k+1].Content)
}
lKeys[z] = fmt.Sprintf("%v-%v-%v",
l.Value.ValueNode.Content[k].Value,
l.Value.ValueNode.Content[k+1].Tag,
fmt.Sprintf("%x", val))
z++
} else {
continue
}
}
z = 0
for k := range r.Value.ValueNode.Content {
if k%2 == 0 {
// if there is no value (value is another map or something else), render the node into yaml and hash it.
// https://github.com/pb33f/libopenapi/issues/61
val := r.Value.ValueNode.Content[k+1].Value
if val == "" {
val = low.HashYAMLNodeSlice(r.Value.ValueNode.Content[k+1].Content)
}
rKeys[z] = fmt.Sprintf("%v-%v-%v",
r.Value.ValueNode.Content[k].Value,
r.Value.ValueNode.Content[k+1].Tag,
fmt.Sprintf("%x", val))
z++
} else {
continue
}
}
sort.Strings(lKeys)
sort.Strings(rKeys)
for k := range lKeys {
if k < len(rKeys) && lKeys[k] != rKeys[k] {
CreateChangeWithEncoding(&changes, Modified, v3.ValueLabel,
l.Value.GetValueNode(), r.Value.GetValueNode(), BreakingModified(CompExample, PropValue), l.Value.GetValue(), r.Value.GetValue())
continue
}
if k >= len(rKeys) {
CreateChangeWithEncoding(&changes, PropertyRemoved, v3.ValueLabel,
l.Value.ValueNode, r.Value.ValueNode, BreakingRemoved(CompExample, PropValue), l.Value.Value, r.Value.Value)
}
}
for k := range rKeys {
if k >= len(lKeys) {
CreateChangeWithEncoding(&changes, PropertyAdded, v3.ValueLabel,
l.Value.ValueNode, r.Value.ValueNode, BreakingAdded(CompExample, PropValue), l.Value.Value, r.Value.Value)
}
}
}
} else {
props = append(props, NewPropertyCheck(CompExample, PropValue,
// Value and DataValue hold any YAML shape, so they are checked with encoding.
CheckPropertiesWithEncoding([]*PropertyCheck{
NewPropertyCheck(CompExample, PropValue,
l.Value.ValueNode, r.Value.ValueNode,
v3.ValueLabel, &changes, l, r))
}
v3.ValueLabel, &changes, l, r),
NewPropertyCheck(CompExample, PropDataValue,
l.DataValue.ValueNode, r.DataValue.ValueNode,
base.DataValueLabel, &changes, l, r),
})

// ExternalValue
props = append(props, NewPropertyCheck(CompExample, PropExternalValue,
l.ExternalValue.ValueNode, r.ExternalValue.ValueNode,
v3.ExternalValue, &changes, l, r))

// DataValue (OpenAPI 3.2+)
props = append(props, NewPropertyCheck(CompExample, PropDataValue,
l.DataValue.ValueNode, r.DataValue.ValueNode,
base.DataValueLabel, &changes, l, r))

// SerializedValue (OpenAPI 3.2+)
props = append(props, NewPropertyCheck(CompExample, PropSerializedValue,
l.SerializedValue.ValueNode, r.SerializedValue.ValueNode,
Expand Down
140 changes: 52 additions & 88 deletions what-changed/model/example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (

"github.com/pb33f/go-yaml"
"github.com/pb33f/testify/assert"
"github.com/pb33f/testify/require"

"github.com/pb33f/libopenapi/datamodel/low"
"github.com/pb33f/libopenapi/datamodel/low/base"
Expand Down Expand Up @@ -44,94 +45,57 @@ func TestCompareExamples_SummaryModified(t *testing.T) {
assert.Equal(t, "cure all", extChanges.Changes[0].New)
}

func TestCompareExamples_Map(t *testing.T) {
// Clear hash cache to ensure deterministic results in concurrent test environments
low.ClearHashCache()
left := `value:
cheesy: bread
pasta: sauce`

right := `value:
cheesy: cakes
pasta: spicy`

var lNode, rNode yaml.Node
_ = yaml.Unmarshal([]byte(left), &lNode)
_ = yaml.Unmarshal([]byte(right), &rNode)

// create low level objects
var lDoc base.Example
var rDoc base.Example
_ = low.BuildModel(lNode.Content[0], &lDoc)
_ = low.BuildModel(rNode.Content[0], &rDoc)
_ = lDoc.Build(context.Background(), nil, lNode.Content[0], nil)
_ = rDoc.Build(context.Background(), nil, rNode.Content[0], nil)

extChanges := CompareExamples(&lDoc, &rDoc)

assert.Equal(t, extChanges.TotalChanges(), 2)
assert.Len(t, extChanges.GetAllChanges(), 2)
assert.Equal(t, 0, extChanges.TotalBreakingChanges())
assert.Equal(t, Modified, extChanges.Changes[0].ChangeType)
}

func TestCompareExamples_MapAdded(t *testing.T) {
// Clear hash cache to ensure deterministic results in concurrent test environments
low.ClearHashCache()
left := `value:
cheesy: bread`

right := `value:
cheesy: bread
pasta: sauce`

var lNode, rNode yaml.Node
_ = yaml.Unmarshal([]byte(left), &lNode)
_ = yaml.Unmarshal([]byte(right), &rNode)

// create low level objects
var lDoc base.Example
var rDoc base.Example
_ = low.BuildModel(lNode.Content[0], &lDoc)
_ = low.BuildModel(rNode.Content[0], &rDoc)
_ = lDoc.Build(context.Background(), nil, lNode.Content[0], nil)
_ = rDoc.Build(context.Background(), nil, rNode.Content[0], nil)

extChanges := CompareExamples(&lDoc, &rDoc)

assert.Equal(t, extChanges.TotalChanges(), 1)
assert.Len(t, extChanges.GetAllChanges(), 1)
assert.Equal(t, 0, extChanges.TotalBreakingChanges())
assert.Equal(t, PropertyAdded, extChanges.Changes[0].ChangeType)
}

func TestCompareExamples_MapRemoved(t *testing.T) {
// Clear hash cache to ensure deterministic results in concurrent test environments
low.ClearHashCache()
left := `value:
cheesy: bread`

right := `value:
cheesy: bread
pasta: sauce`

var lNode, rNode yaml.Node
_ = yaml.Unmarshal([]byte(left), &lNode)
_ = yaml.Unmarshal([]byte(right), &rNode)

// create low level objects
var lDoc base.Example
var rDoc base.Example
_ = low.BuildModel(lNode.Content[0], &lDoc)
_ = low.BuildModel(rNode.Content[0], &rDoc)
_ = lDoc.Build(context.Background(), nil, lNode.Content[0], nil)
_ = rDoc.Build(context.Background(), nil, rNode.Content[0], nil)

extChanges := CompareExamples(&rDoc, &lDoc)

assert.Equal(t, extChanges.TotalChanges(), 1)
assert.Equal(t, 0, extChanges.TotalBreakingChanges())
assert.Equal(t, PropertyRemoved, extChanges.Changes[0].ChangeType)
func TestCompareExamples_StructuredValue(t *testing.T) {
for _, field := range []string{v3.ValueLabel, base.DataValueLabel} {
for _, tc := range []struct {
name, left, right string
}{
{"two members modified", "{id_1: 11, id_2: 21}", "{id_1: 10, id_2: 20}"},
{"member added", "{}", "{id: 1}"},
{"member removed", "{id: 1}", "{}"},
{"sequence reordered inside object", "{items: [1, 2]}", "{items: [2, 1]}"},
{"sequence item modified", "[1, 2]", "[1, 3]"},
{"sequence reordered", "[1, 2]", "[2, 1]"},
{"sequence item added", "[1, 2]", "[1, 2, 3]"},
{"object replaced by sequence", "{a: 1}", "[1]"},
{"sequence replaced by object", "[1]", "{a: 1}"},
} {
t.Run(field+" "+tc.name, func(t *testing.T) {
left := buildTestExample(t, field+": "+tc.left)
right := buildTestExample(t, field+": "+tc.right)
changes := CompareExamples(left, right)
require.NotNil(t, changes)
require.Len(t, changes.GetAllChanges(), 1)
change := changes.Changes[0]
assert.Equal(t, field, change.Property)
assert.Equal(t, Modified, change.ChangeType)
assert.False(t, change.Breaking)
assert.Equal(t, tc.left+"\n", change.OriginalEncoded)
assert.Equal(t, tc.right+"\n", change.NewEncoded)
})
}

t.Run(field+" members reordered", func(t *testing.T) {
left := buildTestExample(t, field+": {a: 1, b: 2}")
reordered := buildTestExample(t, field+": {b: 2, a: 1}")
assert.Nil(t, CompareExamples(left, reordered))
})

t.Run(field+" added and removed", func(t *testing.T) {
absent := buildTestExample(t, "summary: example")
present := buildTestExample(t, "summary: example\n"+field+": {}")
added := CompareExamples(absent, present).GetAllChanges()
require.Len(t, added, 1)
assert.Equal(t, field, added[0].Property)
assert.Equal(t, PropertyAdded, added[0].ChangeType)
assert.Equal(t, "{}\n", added[0].NewEncoded)
removed := CompareExamples(present, absent).GetAllChanges()
require.Len(t, removed, 1)
assert.Equal(t, field, removed[0].Property)
assert.Equal(t, PropertyRemoved, removed[0].ChangeType)
assert.Equal(t, "{}\n", removed[0].OriginalEncoded)
})
}
}

func TestCompareExamples_SummaryAdded(t *testing.T) {
Expand Down
39 changes: 37 additions & 2 deletions what-changed/model/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -857,8 +857,9 @@ func (c *schemaComparison) checkSchemaPropertyChanges(
if rSchema != nil && rSchema.Type.ValueNode != nil {
rnv = rSchema.Type.ValueNode
}
// Type
addCheck(lnv, rnv, v3.TypeLabel, PropType)
if !equalSchemaTypes(lnv, rnv) {
addCheck(lnv, rnv, v3.TypeLabel, PropType)
}
lnv = nil
rnv = nil
}
Expand Down Expand Up @@ -1537,6 +1538,40 @@ func (c *schemaComparison) checkSchemaPropertyChanges(
}
}

// equalSchemaTypes reports whether two type nodes allow the same types, the way Schema.Hash reads them:
// order is ignored, a bare YAML null is the type name 'null', and a single type equals a one entry array.
func equalSchemaTypes(left, right *yaml.Node) bool {
left, right = utils.NodeAlias(left), utils.NodeAlias(right)
if left == nil || right == nil || (left.Kind != yaml.SequenceNode && right.Kind != yaml.SequenceNode) {
return false
}
lt, lok := schemaTypeNames(left)
rt, rok := schemaTypeNames(right)
if !lok || !rok || len(lt) != len(rt) {
return false
}
slices.Sort(lt)
slices.Sort(rt)
return slices.Equal(lt, rt)
}

// schemaTypeNames returns the type names held by a type node, which is a single type or an array of them.
func schemaTypeNames(node *yaml.Node) ([]string, bool) {
items := []*yaml.Node{node}
if node.Kind == yaml.SequenceNode {
items = node.Content
}
names := make([]string, 0, len(items))
for _, item := range items {
name, ok := extractScalarTypeName(utils.NodeAlias(item))
if !ok {
return nil, false
}
names = append(names, name)
}
return names, true
}

func schemasUseEquivalentSimpleScalarUnion(l, r *base.SchemaProxy) bool {
return schemaPairUsesEquivalentSimpleScalarUnion(l, r) ||
schemaPairUsesEquivalentSimpleScalarUnion(r, l)
Expand Down
43 changes: 43 additions & 0 deletions what-changed/model/schema_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2041,6 +2041,49 @@ components:
assert.Equal(t, "bool", changes.AnyOfChanges[0].Changes[0].Original)
}

func TestCompareSchemas_TypeArrayWithDescriptionChange(t *testing.T) {
const prefix = "x-string-type: &text string\n"
const original = "['null', string, number]"
for _, tc := range []struct {
name, left, right string
typeChanged bool
}{
{"reordered", original, "[string, number, 'null']", false},
{"reordered with alias", original, "[*text, number, 'null']", false},
{"narrowed", original, "[string, number]", true},
{"replaced", original, "[string, boolean, 'null']", true},
// A bare YAML null is the type name 'null', the same way Schema.Hash reads it.
{"correct unquoted null", "[null, string, number]", original, false},
{"introduce unquoted null", original, "[null, string, number]", false},
{"reordered unquoted null", "[null, string, number]", "[string, number, null]", false},
{"reordered tilde null", "[~, string, number]", "[string, number, ~]", false},
// A single type means the same as a type array holding only that type.
{"single type to array", "string", "[string]", false},
{"array to single type", "[string]", "string", false},
{"array narrowed to single type", original, "string", true},
{"single type replaced", "string", "number", true},
{"duplicate member swapped", "[string, string, 'null']", "[string, 'null', 'null']", true},
{"member without a type name", "['', string]", "[string, '']", true},
} {
t.Run(tc.name, func(t *testing.T) {
left := buildSchemaProxyFromYAML(t, prefix+"type: "+tc.left)
right := buildSchemaProxyFromYAML(t, prefix+"type: "+tc.right+"\ndescription: Filter operator")
changes := CompareSchemas(left, right)
require.NotNil(t, changes)
properties := make(map[string]bool)
for _, change := range changes.GetAllChanges() {
properties[change.Property] = change.Breaking
}
want := map[string]bool{v3.DescriptionLabel: false}
if tc.typeChanged {
want[v3.TypeLabel] = true
}
assert.Equal(t, want, properties)
assert.Equal(t, len(want), changes.TotalChanges())
})
}
}

// https://github.com/pb33f/openapi-changes/issues/105
func TestCompareSchemas_AnyOfSimpleScalarUnionMatchesTypeArray(t *testing.T) {
// Clear hash cache to ensure deterministic results in concurrent test environments
Expand Down
Loading