Skip to content

Commit

Permalink
Modified Node.clone() to update the parent field of each child to poi…
Browse files Browse the repository at this point in the history
…nt to it's cloned parent (instead of the original nodes as it was). Added a test to validate this.
  • Loading branch information
yevgenin committed Sep 2, 2024
1 parent 71e4170 commit 2828d2b
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
4 changes: 3 additions & 1 deletion node_mutations.go
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,9 @@ func (n *Node) clone() *Node {
dirty: n.dirty,
}
for key, value := range n.children {
node.children[key] = value.clone()
clone := value.clone()
clone.parent = node
node.children[key] = clone
}
return node
}
Expand Down
19 changes: 19 additions & 0 deletions node_mutations_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1380,6 +1380,7 @@ func TestNode_Clone(t *testing.T) {
null := NullNode("")
array := ArrayNode("", []*Node{node, null})
object := ObjectNode("", map[string]*Node{"array": array})
objectWithObject := ObjectNode("", map[string]*Node{"object": object})

tests := []struct {
name string
Expand All @@ -1406,6 +1407,11 @@ func TestNode_Clone(t *testing.T) {
node: object,
json: `{"array":[1.1,null]}`,
},
{
name: "objectWithObject",
node: objectWithObject,
json: `{"object":{"array":[1.1,null]}}`,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
Expand All @@ -1427,10 +1433,23 @@ func TestNode_Clone(t *testing.T) {
} else if string(base) != test.json {
t.Errorf("Marshal() base not match: \nExpected: %s\nActual: %s", test.json, base)
}

validateParent(t, clone)
})
}
}

// validateParent checks if all children have the correct parent, recursively.
func validateParent(t *testing.T, node *Node) {
for _, child := range node.Inheritors() {
if child.Parent() != node {
t.Errorf("Inheritor.Parent() != node")
}

validateParent(t, child)
}
}

func ExampleNode_Clone() {
root := Must(Unmarshal(jsonPathTestData))
nodes, _ := root.JSONPath("$..price")
Expand Down

0 comments on commit 2828d2b

Please sign in to comment.