test_adjacency.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import json
  2. import pytest
  3. import networkx as nx
  4. from networkx.readwrite.json_graph import adjacency_data, adjacency_graph
  5. class TestAdjacency:
  6. def test_graph(self):
  7. G = nx.path_graph(4)
  8. H = adjacency_graph(adjacency_data(G))
  9. assert nx.is_isomorphic(G, H)
  10. def test_graph_attributes(self):
  11. G = nx.path_graph(4)
  12. G.add_node(1, color="red")
  13. G.add_edge(1, 2, width=7)
  14. G.graph["foo"] = "bar"
  15. G.graph[1] = "one"
  16. H = adjacency_graph(adjacency_data(G))
  17. assert H.graph["foo"] == "bar"
  18. assert H.nodes[1]["color"] == "red"
  19. assert H[1][2]["width"] == 7
  20. d = json.dumps(adjacency_data(G))
  21. H = adjacency_graph(json.loads(d))
  22. assert H.graph["foo"] == "bar"
  23. assert H.graph[1] == "one"
  24. assert H.nodes[1]["color"] == "red"
  25. assert H[1][2]["width"] == 7
  26. def test_digraph(self):
  27. G = nx.DiGraph()
  28. nx.add_path(G, [1, 2, 3])
  29. H = adjacency_graph(adjacency_data(G))
  30. assert H.is_directed()
  31. assert nx.is_isomorphic(G, H)
  32. def test_multidigraph(self):
  33. G = nx.MultiDiGraph()
  34. nx.add_path(G, [1, 2, 3])
  35. H = adjacency_graph(adjacency_data(G))
  36. assert H.is_directed()
  37. assert H.is_multigraph()
  38. def test_multigraph(self):
  39. G = nx.MultiGraph()
  40. G.add_edge(1, 2, key="first")
  41. G.add_edge(1, 2, key="second", color="blue")
  42. H = adjacency_graph(adjacency_data(G))
  43. assert nx.is_isomorphic(G, H)
  44. assert H[1][2]["second"]["color"] == "blue"
  45. def test_exception(self):
  46. with pytest.raises(nx.NetworkXError):
  47. G = nx.MultiDiGraph()
  48. attrs = {"id": "node", "key": "node"}
  49. adjacency_data(G, attrs)