1 #!/usr/bin/env python 2 from nose.tools import * 3 import networkx as nx 4 from networkx import NetworkXError 5 6 class TestWeaklyConnected: 7 8 def setUp(self): 9 self.gc=[] 10 G=nx.DiGraph() 11 G.add_edges_from([(1,2),(2,3),(2,8),(3,4),(3,7), 12 (4,5),(5,3),(5,6),(7,4),(7,6),(8,1),(8,7)]) 13 C=[[3, 4, 5, 7], [1, 2, 8], [6]] 14 self.gc.append((G,C)) 15 16 G= nx.DiGraph() 17 G.add_edges_from([(1,2),(1,3),(1,4),(4,2),(3,4),(2,3)]) 18 C = [[2, 3, 4],[1]] 19 self.gc.append((G,C)) 20 21 G = nx.DiGraph() 22 G.add_edges_from([(1,2),(2,3),(3,2),(2,1)]) 23 C = [[1, 2, 3]] 24 self.gc.append((G,C)) 25 26 # Eppstein's tests 27 G = nx.DiGraph({ 0:[1],1:[2,3],2:[4,5],3:[4,5],4:[6],5:[],6:[]}) 28 C = [[0],[1],[2],[3],[4],[5],[6]] 29 self.gc.append((G,C)) 30 31 G = nx.DiGraph({0:[1],1:[2,3,4],2:[0,3],3:[4],4:[3]}) 32 C = [[0,1,2],[3,4]] 33 self.gc.append((G,C)) 34 35 36 def test_weakly_connected_components(self): 37 wcc=nx.weakly_connected_components 38 cc=nx.connected_components 39 for G,C in self.gc: 40 U=G.to_undirected() 41 w=sorted([sorted(g) for g in wcc(G)]) 42 c=sorted([sorted(g) for g in cc(U)]) 43 assert_equal(w,c) 44 45 def test_number_weakly_connected_components(self): 46 wcc=nx.number_weakly_connected_components 47 cc=nx.number_connected_components 48 for G,C in self.gc: 49 U=G.to_undirected() 50 w=wcc(G) 51 c=cc(U) 52 assert_equal(w,c) 53 54 def test_weakly_connected_component_subgraphs(self): 55 wcc=nx.weakly_connected_component_subgraphs 56 cc=nx.connected_component_subgraphs 57 for G,C in self.gc: 58 U=G.to_undirected() 59 w=sorted([sorted(g.nodes()) for g in wcc(G)]) 60 c=sorted([sorted(g.nodes()) for g in cc(U)]) 61 assert_equal(w,c) 62 G,C=self.gc[0] 63 G.add_edge(1,2,eattr='red') 64 G.node[1]['nattr']='blue' 65 G.graph['gattr']='green' 66 sgs=wcc(G)[0] 67 assert_equal(sgs[1][2]['eattr'],'red') 68 assert_equal(sgs.node[1]['nattr'],'blue') 69 assert_equal(sgs.graph['gattr'],'green') 70 sgs[1][2]['eattr']='blue' 71 assert_equal(G[1][2]['eattr'],'red') 72 assert_equal(sgs[1][2]['eattr'],'blue') 73 74 def test_is_weakly_connected(self): 75 wcc=nx.is_weakly_connected 76 cc=nx.is_connected 77 for G,C in self.gc: 78 U=G.to_undirected() 79 assert_equal(wcc(G),cc(U)) 80 81 82 def test_connected_raise(self): 83 G=nx.Graph() 84 assert_raises(NetworkXError,nx.weakly_connected_components,G) 85 assert_raises(NetworkXError,nx.number_weakly_connected_components,G) 86 assert_raises(NetworkXError,nx.weakly_connected_component_subgraphs,G) 87 assert_raises(NetworkXError,nx.is_weakly_connected,G) 88 89