test_pydot.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. """Unit tests for pydot drawing functions."""
  2. import os
  3. import tempfile
  4. from io import StringIO
  5. import pytest
  6. import networkx as nx
  7. from networkx.utils import graphs_equal
  8. pydot = pytest.importorskip("pydot")
  9. @pytest.mark.xfail
  10. class TestPydot:
  11. def pydot_checks(self, G, prog):
  12. """
  13. Validate :mod:`pydot`-based usage of the passed NetworkX graph with the
  14. passed basename of an external GraphViz command (e.g., `dot`, `neato`).
  15. """
  16. # Set the name of this graph to... "G". Failing to do so will
  17. # subsequently trip an assertion expecting this name.
  18. G.graph["name"] = "G"
  19. # Add arbitrary nodes and edges to the passed empty graph.
  20. G.add_edges_from([("A", "B"), ("A", "C"), ("B", "C"), ("A", "D")])
  21. G.add_node("E")
  22. # Validate layout of this graph with the passed GraphViz command.
  23. graph_layout = nx.nx_pydot.pydot_layout(G, prog=prog)
  24. assert isinstance(graph_layout, dict)
  25. # Convert this graph into a "pydot.Dot" instance.
  26. P = nx.nx_pydot.to_pydot(G)
  27. # Convert this "pydot.Dot" instance back into a graph of the same type.
  28. G2 = G.__class__(nx.nx_pydot.from_pydot(P))
  29. # Validate the original and resulting graphs to be the same.
  30. assert graphs_equal(G, G2)
  31. fd, fname = tempfile.mkstemp()
  32. # Serialize this "pydot.Dot" instance to a temporary file in dot format
  33. P.write_raw(fname)
  34. # Deserialize a list of new "pydot.Dot" instances back from this file.
  35. Pin_list = pydot.graph_from_dot_file(path=fname, encoding="utf-8")
  36. # Validate this file to contain only one graph.
  37. assert len(Pin_list) == 1
  38. # The single "pydot.Dot" instance deserialized from this file.
  39. Pin = Pin_list[0]
  40. # Sorted list of all nodes in the original "pydot.Dot" instance.
  41. n1 = sorted(p.get_name() for p in P.get_node_list())
  42. # Sorted list of all nodes in the deserialized "pydot.Dot" instance.
  43. n2 = sorted(p.get_name() for p in Pin.get_node_list())
  44. # Validate these instances to contain the same nodes.
  45. assert n1 == n2
  46. # Sorted list of all edges in the original "pydot.Dot" instance.
  47. e1 = sorted((e.get_source(), e.get_destination()) for e in P.get_edge_list())
  48. # Sorted list of all edges in the original "pydot.Dot" instance.
  49. e2 = sorted((e.get_source(), e.get_destination()) for e in Pin.get_edge_list())
  50. # Validate these instances to contain the same edges.
  51. assert e1 == e2
  52. # Deserialize a new graph of the same type back from this file.
  53. Hin = nx.nx_pydot.read_dot(fname)
  54. Hin = G.__class__(Hin)
  55. # Validate the original and resulting graphs to be the same.
  56. assert graphs_equal(G, Hin)
  57. os.close(fd)
  58. os.unlink(fname)
  59. def test_undirected(self):
  60. self.pydot_checks(nx.Graph(), prog="neato")
  61. def test_directed(self):
  62. self.pydot_checks(nx.DiGraph(), prog="dot")
  63. def test_read_write(self):
  64. G = nx.MultiGraph()
  65. G.graph["name"] = "G"
  66. G.add_edge("1", "2", key="0") # read assumes strings
  67. fh = StringIO()
  68. nx.nx_pydot.write_dot(G, fh)
  69. fh.seek(0)
  70. H = nx.nx_pydot.read_dot(fh)
  71. assert graphs_equal(G, H)
  72. def test_pydot_issue_258():
  73. G = nx.Graph([("Example:A", 1)])
  74. with pytest.raises(ValueError):
  75. nx.nx_pydot.to_pydot(G)
  76. with pytest.raises(ValueError):
  77. nx.nx_pydot.pydot_layout(G)
  78. G = nx.Graph()
  79. G.add_node("1.2", style="filled", fillcolor="red:yellow")
  80. with pytest.raises(ValueError):
  81. nx.nx_pydot.to_pydot(G)
  82. G.remove_node("1.2")
  83. G.add_node("1.2", style="filled", fillcolor='"red:yellow"')
  84. assert (
  85. G.nodes.data() == nx.nx_pydot.from_pydot(nx.nx_pydot.to_pydot(G)).nodes.data()
  86. )
  87. G = nx.DiGraph()
  88. G.add_edge("1", "2", foo="bar:1")
  89. with pytest.raises(ValueError):
  90. nx.nx_pydot.to_pydot(G)
  91. G = nx.DiGraph()
  92. G.add_edge("1", "2", foo='"bar:1"')
  93. assert G["1"]["2"] == nx.nx_pydot.from_pydot(nx.nx_pydot.to_pydot(G))["1"]["2"]
  94. G = nx.MultiGraph()
  95. G.add_edge("1", "2", foo="b:1")
  96. G.add_edge("1", "2", bar="foo:foo")
  97. with pytest.raises(ValueError):
  98. nx.nx_pydot.to_pydot(G)
  99. G = nx.MultiGraph()
  100. G.add_edge("1", "2", foo='"b:1"')
  101. G.add_edge("1", "2", bar='"foo:foo"')
  102. # Keys as integers aren't preserved in the conversion. They are read as strings.
  103. assert [attr for _, _, attr in G.edges.data()] == [
  104. attr
  105. for _, _, attr in nx.nx_pydot.from_pydot(nx.nx_pydot.to_pydot(G)).edges.data()
  106. ]
  107. G = nx.Graph()
  108. G.add_edge("1", "2")
  109. G["1"]["2"]["f:oo"] = "bar"
  110. with pytest.raises(ValueError):
  111. nx.nx_pydot.to_pydot(G)
  112. G = nx.Graph()
  113. G.add_edge("1", "2")
  114. G["1"]["2"]['"f:oo"'] = "bar"
  115. assert G["1"]["2"] == nx.nx_pydot.from_pydot(nx.nx_pydot.to_pydot(G))["1"]["2"]
  116. G = nx.Graph([('"Example:A"', 1)])
  117. layout = nx.nx_pydot.pydot_layout(G)
  118. assert isinstance(layout, dict)
  119. @pytest.mark.parametrize(
  120. "graph_type", [nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph]
  121. )
  122. def test_hashable_pydot(graph_type):
  123. # gh-5790
  124. G = graph_type()
  125. G.add_edge("5", frozenset([1]), t='"Example:A"', l=False)
  126. G.add_edge("1", 2, w=True, t=("node1",), l=frozenset(["node1"]))
  127. G.add_edge("node", (3, 3), w="string")
  128. assert [
  129. {"t": '"Example:A"', "l": "False"},
  130. {"w": "True", "t": "('node1',)", "l": "frozenset({'node1'})"},
  131. {"w": "string"},
  132. ] == [
  133. attr
  134. for _, _, attr in nx.nx_pydot.from_pydot(nx.nx_pydot.to_pydot(G)).edges.data()
  135. ]
  136. assert {str(i) for i in G.nodes()} == set(
  137. nx.nx_pydot.from_pydot(nx.nx_pydot.to_pydot(G)).nodes
  138. )
  139. def test_pydot_numrical_name():
  140. G = nx.Graph()
  141. G.add_edges_from([("A", "B"), (0, 1)])
  142. graph_layout = nx.nx_pydot.pydot_layout(G, prog="dot")
  143. assert isinstance(graph_layout, dict)
  144. assert "0" not in graph_layout
  145. assert 0 in graph_layout
  146. assert "1" not in graph_layout
  147. assert 1 in graph_layout
  148. assert "A" in graph_layout
  149. assert "B" in graph_layout