test_tree.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import json
  2. import pytest
  3. import networkx as nx
  4. from networkx.readwrite.json_graph import tree_data, tree_graph
  5. def test_graph():
  6. G = nx.DiGraph()
  7. G.add_nodes_from([1, 2, 3], color="red")
  8. G.add_edge(1, 2, foo=7)
  9. G.add_edge(1, 3, foo=10)
  10. G.add_edge(3, 4, foo=10)
  11. H = tree_graph(tree_data(G, 1))
  12. assert nx.is_isomorphic(G, H)
  13. def test_graph_attributes():
  14. G = nx.DiGraph()
  15. G.add_nodes_from([1, 2, 3], color="red")
  16. G.add_edge(1, 2, foo=7)
  17. G.add_edge(1, 3, foo=10)
  18. G.add_edge(3, 4, foo=10)
  19. H = tree_graph(tree_data(G, 1))
  20. assert H.nodes[1]["color"] == "red"
  21. d = json.dumps(tree_data(G, 1))
  22. H = tree_graph(json.loads(d))
  23. assert H.nodes[1]["color"] == "red"
  24. def test_exceptions():
  25. with pytest.raises(TypeError, match="is not a tree."):
  26. G = nx.complete_graph(3)
  27. tree_data(G, 0)
  28. with pytest.raises(TypeError, match="is not directed."):
  29. G = nx.path_graph(3)
  30. tree_data(G, 0)
  31. with pytest.raises(TypeError, match="is not weakly connected."):
  32. G = nx.path_graph(3, create_using=nx.DiGraph)
  33. G.add_edge(2, 0)
  34. G.add_node(3)
  35. tree_data(G, 0)
  36. with pytest.raises(nx.NetworkXError, match="must be different."):
  37. G = nx.MultiDiGraph()
  38. G.add_node(0)
  39. tree_data(G, 0, ident="node", children="node")