1 #!/usr/bin/env python 2 from nose.tools import * 3 import networkx as nx 4 from networkx import convert_node_labels_to_integers as cnlti 5 from networkx import NetworkXError 6 7 class TestConnected: 8 9 def setUp(self): 10 G1=cnlti(nx.grid_2d_graph(2,2),first_label=0,ordering="sorted") 11 G2=cnlti(nx.lollipop_graph(3,3),first_label=4,ordering="sorted") 12 G3=cnlti(nx.house_graph(),first_label=10,ordering="sorted") 13 self.G=nx.union(G1,G2) 14 self.G=nx.union(self.G,G3) 15 self.DG=nx.DiGraph([(1,2),(1,3),(2,3)]) 16 self.grid=cnlti(nx.grid_2d_graph(4,4),first_label=1) 17 18 def test_connected_components(self): 19 cc=nx.connected_components 20 G=self.G 21 C=[[0, 1, 2, 3], [4, 5, 6, 7, 8, 9], [10, 11, 12, 13, 14]] 22 assert_equal(sorted([sorted(g) for g in cc(G)]),sorted(C)) 23 24 def test_number_connected_components(self): 25 ncc=nx.number_connected_components 26 assert_equal(ncc(self.G),3) 27 28 def test_number_connected_components2(self): 29 ncc=nx.number_connected_components 30 assert_equal(ncc(self.grid),1) 31 32 def test_connected_components2(self): 33 cc=nx.connected_components 34 G=self.grid 35 C=[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]] 36 assert_equal(sorted([sorted(g) for g in cc(G)]),sorted(C)) 37 38 def test_node_connected_components(self): 39 ncc=nx.node_connected_component 40 G=self.grid 41 C=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] 42 assert_equal(sorted(ncc(G,1)),sorted(C)) 43 44 def test_connected_component_subgraphs(self): 45 G=self.grid 46 G.add_edge(1,2,eattr='red') # test attributes copied to subgraphs 47 G.node[1]['nattr']='blue' 48 G.graph['gattr']='green' 49 ccs=nx.connected_component_subgraphs(G) 50 assert_equal(len(ccs),1) 51 sg=ccs[0] 52 assert_equal(sorted(sg.nodes()),list(range(1,17))) 53 assert_equal(sg[1][2]['eattr'],'red') 54 assert_equal(sg.node[1]['nattr'],'blue') 55 assert_equal(sg.graph['gattr'],'green') 56 sg[1][2]['eattr']='blue' 57 assert_equal(G[1][2]['eattr'],'red') 58 assert_equal(sg[1][2]['eattr'],'blue') 59 60 61 def test_is_connected(self): 62 assert_true(nx.is_connected(self.grid)) 63 G=nx.Graph() 64 G.add_nodes_from([1,2]) 65 assert_false(nx.is_connected(G)) 66 67 def test_connected_raise(self): 68 assert_raises(NetworkXError,nx.connected_components,self.DG) 69 assert_raises(NetworkXError,nx.number_connected_components,self.DG) 70 assert_raises(NetworkXError,nx.connected_component_subgraphs,self.DG) 71 assert_raises(NetworkXError,nx.node_connected_component,self.DG,1) 72 assert_raises(NetworkXError,nx.is_connected,self.DG) 73