[core] Add Graph.copy method

Add a new method to create a copy of a graph instance, relying on
chaining serialization and deserialization operations.
Add test suite to validate its behavior, and the underlying serialization processes.
This commit is contained in:
Yann Lanthony 2025-02-06 16:46:04 +01:00
parent d54ba012a0
commit bfc642e2dc
2 changed files with 33 additions and 0 deletions

View file

@ -1351,6 +1351,12 @@ class Graph(BaseObject):
def asString(self): def asString(self):
return str(self.toDict()) return str(self.toDict())
def copy(self) -> "Graph":
"""Create a copy of this Graph instance."""
graph = Graph("")
graph._deserialize(self.serialize())
return graph
def serialize(self, asTemplate: bool = False) -> dict: def serialize(self, asTemplate: bool = False) -> dict:
"""Serialize this Graph instance. """Serialize this Graph instance.

View file

@ -214,3 +214,30 @@ class TestGraphPartialSerialization:
assert len(otherGraph.compatibilityNodes) == 0 assert len(otherGraph.compatibilityNodes) == 0
assert len(otherGraph.nodes) == 1 assert len(otherGraph.nodes) == 1
assert len(otherGraph.edges) == 0 assert len(otherGraph.edges) == 0
class TestGraphCopy:
def test_graphCopyIsIdenticalToOriginalGraph(self):
graph = Graph("")
with registeredNodeTypes([SimpleNode]):
nodeA = graph.addNewNode(SimpleNode.__name__)
nodeB = graph.addNewNode(SimpleNode.__name__)
graph.addEdge(nodeA.output, nodeB.input)
graphCopy = graph.copy()
assert compareGraphsContent(graph, graphCopy)
def test_graphCopyWithUnknownNodeTypesDiffersFromOriginalGraph(self):
graph = Graph("")
with registeredNodeTypes([SimpleNode]):
nodeA = graph.addNewNode(SimpleNode.__name__)
nodeB = graph.addNewNode(SimpleNode.__name__)
graph.addEdge(nodeA.output, nodeB.input)
graphCopy = graph.copy()
assert not compareGraphsContent(graph, graphCopy)