1 #!/usr/bin/env python 2 import io 3 from nose.tools import * 4 from nose import SkipTest 5 import networkx 6 7 class TestGraph(object): 8 @classmethod 9 def setupClass(cls): 10 global pyparsing 11 try: 12 import pyparsing 13 except ImportError: 14 try: 15 import matplotlib.pyparsing as pyparsing 16 except: 17 raise SkipTest('gml test: pyparsing not available.') 18 19 def setUp(self): 20 self.simple_data="""Creator me 21 graph [ 22 comment "This is a sample graph" 23 directed 1 24 IsPlanar 1 25 pos [ x 0 y 1 ] 26 node [ 27 id 1 28 label "Node 1" 29 pos [ x 1 y 1 ] 30 ] 31 node [ 32 id 2 33 pos [ x 1 y 2 ] 34 label "Node 2" 35 ] 36 node [ 37 id 3 38 label "Node 3" 39 pos [ x 1 y 3 ] 40 ] 41 edge [ 42 source 1 43 target 2 44 label "Edge from node 1 to node 2" 45 color [line "blue" thickness 3] 46 47 ] 48 edge [ 49 source 2 50 target 3 51 label "Edge from node 2 to node 3" 52 ] 53 edge [ 54 source 3 55 target 1 label 56 "Edge from node 3 to node 1" 57 ] 58 ] 59 """ 60 def test_parse_gml(self): 61 G=networkx.parse_gml(self.simple_data,relabel=True) 62 assert_equals(sorted(G.nodes()),\ 63 ['Node 1', 'Node 2', 'Node 3']) 64 assert_equals( [e for e in sorted(G.edges())],\ 65 [('Node 1', 'Node 2'), 66 ('Node 2', 'Node 3'), 67 ('Node 3', 'Node 1')]) 68 69 assert_equals( [e for e in sorted(G.edges(data=True))],\ 70 [('Node 1', 'Node 2', 71 {'color': {'line': 'blue', 'thickness': 3}, 72 'label': 'Edge from node 1 to node 2'}), 73 ('Node 2', 'Node 3', 74 {'label': 'Edge from node 2 to node 3'}), 75 ('Node 3', 'Node 1', 76 {'label': 'Edge from node 3 to node 1'})]) 77 78 79 def test_read_gml(self): 80 import os,tempfile 81 (fd,fname)=tempfile.mkstemp() 82 fh=open(fname,'w') 83 fh.write(self.simple_data) 84 fh.close() 85 Gin=networkx.read_gml(fname,relabel=True) 86 G=networkx.parse_gml(self.simple_data,relabel=True) 87 assert_equals( sorted(G.nodes(data=True)), sorted(Gin.nodes(data=True))) 88 assert_equals( sorted(G.edges(data=True)), sorted(Gin.edges(data=True))) 89 os.close(fd) 90 os.unlink(fname) 91 92 def test_relabel_duplicate(self): 93 data=""" 94 graph 95 [ 96 label "" 97 directed 1 98 node 99 [ 100 id 0 101 label "same" 102 ] 103 node 104 [ 105 id 1 106 label "same" 107 ] 108 ] 109 """ 110 fh = io.BytesIO(data.encode('UTF-8')) 111 fh.seek(0) 112 assert_raises(networkx.NetworkXError,networkx.read_gml,fh,relabel=True) 113 114 def test_bool(self): 115 G=networkx.Graph() 116 G.add_node(1,on=True) 117 G.add_edge(1,2,on=False) 118 data = '\n'.join(list(networkx.generate_gml(G))) 119 answer ="""graph [ 120 node [ 121 id 0 122 label 1 123 on 1 124 ] 125 node [ 126 id 1 127 label 2 128 ] 129 edge [ 130 source 0 131 target 1 132 on 0 133 ] 134 ]""" 135 assert_equal(data,answer) 136