Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed Node.Clone() to update the correct parents for children #74

Merged
merged 1 commit into from
Sep 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading