Skip to content

Commit

Permalink
Added missing validation for adding sequences to maps #1341
Browse files Browse the repository at this point in the history
  • Loading branch information
mikefarah committed Sep 16, 2022
1 parent 9b69618 commit b204772
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
5 changes: 4 additions & 1 deletion pkg/yqlib/operator_add.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,9 @@ func add(d *dataTreeNavigator, context Context, lhs *CandidateNode, rhs *Candida

switch lhsNode.Kind {
case yaml.MappingNode:
if rhs.Node.Kind != yaml.MappingNode {
return nil, fmt.Errorf("%v (%v) cannot be added to a %v (%v)", rhs.Node.Tag, rhs.GetNicePath(), lhsNode.Tag, lhs.GetNicePath())
}
addMaps(target, lhs, rhs)
case yaml.SequenceNode:
if err := addSequences(target, lhs, rhs); err != nil {
Expand All @@ -70,7 +73,7 @@ func add(d *dataTreeNavigator, context Context, lhs *CandidateNode, rhs *Candida

case yaml.ScalarNode:
if rhs.Node.Kind != yaml.ScalarNode {
return nil, fmt.Errorf("%v (%v) cannot be added to a %v", rhs.Node.Tag, rhs.Path, lhsNode.Tag)
return nil, fmt.Errorf("%v (%v) cannot be added to a %v (%v)", rhs.Node.Tag, rhs.GetNicePath(), lhsNode.Tag, lhs.GetNicePath())
}
target.Node.Kind = yaml.ScalarNode
target.Node.Style = lhsNode.Style
Expand Down
14 changes: 14 additions & 0 deletions pkg/yqlib/operator_add_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,20 @@ var addOperatorScenarios = []expressionScenario{
"D0, P[], (doc)::a: &horse [1, 2]\n",
},
},
{
skipDoc: true,
description: "Add sequence to map",
document: "a: {x: cool}",
expression: `.a += [2]`,
expectedError: "!!seq () cannot be added to a !!map (a)",
},
{
skipDoc: true,
description: "Add sequence to scalar",
document: "a: cool",
expression: `.a += [2]`,
expectedError: "!!seq () cannot be added to a !!str (a)",
},
}

func TestAddOperatorScenarios(t *testing.T) {
Expand Down
6 changes: 5 additions & 1 deletion pkg/yqlib/operators_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,11 @@ func testScenario(t *testing.T, s *expressionScenario) {
context, err := NewDataTreeNavigator().GetMatchingNodes(Context{MatchingNodes: inputs}, node)

if s.expectedError != "" {
test.AssertResultComplexWithContext(t, s.expectedError, err.Error(), fmt.Sprintf("desc: %v\nexp: %v\ndoc: %v", s.description, s.expression, s.document))
if err == nil {
t.Errorf("Expected error '%v' but it worked!", s.expectedError)
} else {
test.AssertResultComplexWithContext(t, s.expectedError, err.Error(), fmt.Sprintf("desc: %v\nexp: %v\ndoc: %v", s.description, s.expression, s.document))
}
return
}

Expand Down

0 comments on commit b204772

Please sign in to comment.