Added missing validation for adding sequences to maps #1341

This commit is contained in:
Mike Farah 2022-09-16 10:04:48 +10:00
parent 9b6961875e
commit b20477210f
3 changed files with 23 additions and 2 deletions

View File

@ -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 {
@ -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

View File

@ -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) {

View File

@ -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
}