Skip to content

Commit b204772

Browse files
committed
Added missing validation for adding sequences to maps #1341
1 parent 9b69618 commit b204772

File tree

3 files changed

+23
-2
lines changed

3 files changed

+23
-2
lines changed

pkg/yqlib/operator_add.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,9 @@ func add(d *dataTreeNavigator, context Context, lhs *CandidateNode, rhs *Candida
6262

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

7174
case yaml.ScalarNode:
7275
if rhs.Node.Kind != yaml.ScalarNode {
73-
return nil, fmt.Errorf("%v (%v) cannot be added to a %v", rhs.Node.Tag, rhs.Path, lhsNode.Tag)
76+
return nil, fmt.Errorf("%v (%v) cannot be added to a %v (%v)", rhs.Node.Tag, rhs.GetNicePath(), lhsNode.Tag, lhs.GetNicePath())
7477
}
7578
target.Node.Kind = yaml.ScalarNode
7679
target.Node.Style = lhsNode.Style

pkg/yqlib/operator_add_test.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -350,6 +350,20 @@ var addOperatorScenarios = []expressionScenario{
350350
"D0, P[], (doc)::a: &horse [1, 2]\n",
351351
},
352352
},
353+
{
354+
skipDoc: true,
355+
description: "Add sequence to map",
356+
document: "a: {x: cool}",
357+
expression: `.a += [2]`,
358+
expectedError: "!!seq () cannot be added to a !!map (a)",
359+
},
360+
{
361+
skipDoc: true,
362+
description: "Add sequence to scalar",
363+
document: "a: cool",
364+
expression: `.a += [2]`,
365+
expectedError: "!!seq () cannot be added to a !!str (a)",
366+
},
353367
}
354368

355369
func TestAddOperatorScenarios(t *testing.T) {

pkg/yqlib/operators_test.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,11 @@ func testScenario(t *testing.T, s *expressionScenario) {
100100
context, err := NewDataTreeNavigator().GetMatchingNodes(Context{MatchingNodes: inputs}, node)
101101

102102
if s.expectedError != "" {
103-
test.AssertResultComplexWithContext(t, s.expectedError, err.Error(), fmt.Sprintf("desc: %v\nexp: %v\ndoc: %v", s.description, s.expression, s.document))
103+
if err == nil {
104+
t.Errorf("Expected error '%v' but it worked!", s.expectedError)
105+
} else {
106+
test.AssertResultComplexWithContext(t, s.expectedError, err.Error(), fmt.Sprintf("desc: %v\nexp: %v\ndoc: %v", s.description, s.expression, s.document))
107+
}
104108
return
105109
}
106110

0 commit comments

Comments
 (0)