From b20477210fecb787d5119af995e2a3f54693535b Mon Sep 17 00:00:00 2001 From: Mike Farah Date: Fri, 16 Sep 2022 10:04:48 +1000 Subject: [PATCH] Added missing validation for adding sequences to maps #1341 --- pkg/yqlib/operator_add.go | 5 ++++- pkg/yqlib/operator_add_test.go | 14 ++++++++++++++ pkg/yqlib/operators_test.go | 6 +++++- 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/pkg/yqlib/operator_add.go b/pkg/yqlib/operator_add.go index 5c9edbe3..6b8ae43e 100644 --- a/pkg/yqlib/operator_add.go +++ b/pkg/yqlib/operator_add.go @@ -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 diff --git a/pkg/yqlib/operator_add_test.go b/pkg/yqlib/operator_add_test.go index cd19e16d..71a1a0d5 100644 --- a/pkg/yqlib/operator_add_test.go +++ b/pkg/yqlib/operator_add_test.go @@ -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) { diff --git a/pkg/yqlib/operators_test.go b/pkg/yqlib/operators_test.go index 92b2caeb..a3256dea 100644 --- a/pkg/yqlib/operators_test.go +++ b/pkg/yqlib/operators_test.go @@ -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 }